0
<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 ?

2
  • window[fn](). Remove the jQuery stuff from your call. Commented Oct 19, 2018 at 21:05
  • @Taplar, it works, thanks Commented Oct 19, 2018 at 21:06

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.