如何从数据属性执行功能

时间:2018-07-23 06:40:27

标签: javascript jquery

<div id='dgok' data-fn="delbanner('banners')">OK</div>

js

$('#dgok').click(function(){
    let fn = $(this).attr('data-fn');
    console.log(fn) // delbanner('banners')
    fn();
});

错误:

Uncaught TypeError: fn is not a function

在这种情况下如何执行delbanner('banners')(单击dgok)?

6 个答案:

答案 0 :(得分:1)

避免使用eval,您可以尝试基于通过某些容器(例如,window)访问函数的方法:

const fnContainer = window;
$('#dgok').click(function(){
    const fn = $(this).attr('data-fn');
    const fnName = fn.substring(0, fn.indexOf('(')); // 'delbanner'
    const fnArg = fn.substring(fn.indexOf('(') + 2, fn.length - 2); // 'banners'
    if (typeof fnContainer[fnName] === 'function') {
      fnContainer[fnName].apply(fnContainer, [fnArg]); // window[fnName](fnArg);
    }
});

在这里,我假设您的函数是在window上定义的,并且具有1个字符串参数。


在单独的数据属性中具有函数自变量,该方法可能看起来更简单

const fnContainer = window;
$('#dgok').click(function(){
    const fnName = $(this).attr('data-fn');
    const fnArg = $(this).attr('data-arg');
    if (typeof fnContainer[fnName] === 'function') {
      fnContainer[fnName].apply(fnContainer, [fnArg]); // window[fnName](fnArg);
    }
});

答案 1 :(得分:0)

您可以使用eval,但这绝不是一个好主意。永远

let fn = $(this).attr('data-fn');
eval(fn) // since fn is a string. it will evaluate whatever is in that string

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/eval

答案 2 :(得分:0)

您需要使用eval(fn)将其视为函数调用:

$('#dgok').click(function(){
    let fn = $(this).attr('data-fn');
    console.log(fn) // delbanner('banners')
    eval(fn);
});

function delbanner(param){
  console.log(param);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='dgok' data-fn="delbanner('banners')">OK</div>

答案 3 :(得分:0)

  

使用评估

尝试一下::)

$('#dgok').click(function(){
    let fn = $(this).attr('data-fn');
    console.log(fn); 
    eval(fn);
});

答案 4 :(得分:0)

您可以使用eval

function delbanner() {
  console.log('m')
}
$('#dgok').click(function() {
  console.log('a')
  let fn = $(this).attr('data-fn');
  eval(fn);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='dgok' data-fn="delbanner('banners')">OK</div>

答案 5 :(得分:0)

此错误是正确的,如果fn不起作用。

使用此

$('#dgok').click(function(){
    let fn = () => $(this).attr('data-fn');
    console.log(fn) // delbanner('banners')
    fn();
});