user7461846
user7461846

Reputation:

call a function using data attribute

<div class='cmenu esc' id='cma'>
<div class='cmitem' data-fn='itemcut'>CUT</div>
<div class='cmitem' data-fn='itempaste'>PASTE</div>
<div class='cmitem' data-fn='itemdel'>DELETE</div>
</div>

js

$('.cmitem').click(function(){
    var fn = $(this).attr('data-fn');
    $(window)[fn]();
});

function itemcut(){
    console.log('test');
}

Error: Uncaught TypeError: $(...).fn is not a function

So how to call a function this way ?

Upvotes: 0

Views: 44

Answers (1)

Taplar
Taplar

Reputation: 24965

jQuery does not directly expose Element properites. You have to use the attr() or prop() or data() methods. However, there is no point in using jQuery on the window in this case. Just reference it directly.

$('.cmitem').click(function() {
  //changed to use data() rather than attr()
  var fn = $(this).data('fn');
  var targetFunction = window[fn];
  
  //added some safety checking
  if (typeof targetFunction === 'function') {
    targetFunction();
  }
});

function itemcut() {
  console.log('test');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='cmenu esc' id='cma'>
  <div class='cmitem' data-fn='itemcut'>CUT</div>
  <div class='cmitem' data-fn='itempaste'>PASTE</div>
  <div class='cmitem' data-fn='itemdel'>DELETE</div>
</div>

Upvotes: 3

Related Questions