使用数据属性调用函数

时间:2018-10-19 21:04:13

标签: jquery

<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');
}

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

那么如何以这种方式调用函数?

1 个答案:

答案 0 :(得分:3)

jQuery不会直接公开Element属性。您必须使用attr()prop()data()方法。但是,在这种情况下,在窗口上使用jQuery毫无意义。只需直接引用即可。

$('.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>