使用jquery从HTML5数据元素中获取并执行函数+参数

get and performing function + parameters from HTML5 data- element with jquery

本文关键字:执行 函数 参数 获取 jquery HTML5 数据 元素 使用      更新时间:2023-09-26

我正在制作一个phonegap程序,由于延迟400毫秒,我想使用.on('tap')事件而不是onClick="blah(param1,param2)"。我想做的是给一个"可点击"项目的列表一个"button1"类,每个项目给它一个data-meth="dosomething3()",然后在点击某个项目时检索它。到目前为止,我的示例不使用tap,而是使用click。

       <script>
    $(document).ready(function() {
    console.log('document ready');
    $(".button1").on('click', function(e){ //this will changed to 'tap' eventually
    e.preventDefault();
    console.log("logged click");
    var tempp=$(this).data("meth");
    alert(tempp);
    tempp; // thought this would call the function as it is written in the data-meth value but it doesn't
    });
    });
    function dosomething(){
    console.log('dosomething called');
    }
function dosomething(var1,var2){
alert('hello:' +var1+' just showing var2'+var2);
}
    </script>
My simple html is 
    <ul>
    <li style="text-align:center" class="button1" data-meth="dosomething()" >One</li>
    <li style="text-align:center"  class="button1" data-meth="dosomething2(var1,var2)">Two</li>
    <li style="text-align:center" class="button1" data-meth="dosomething3()">Three</li>
    </ul>

我如何获取和调用基于函数的或存储在数据甲基值中的内容?

在我的脑海中:

$(".button1").click(function() {
    var functionName = $(this).attr("data-meth").split("(")[0];
    var functionParams = $(this).attr("data-meth").split(")")[0].split[","];
    window[functionName](functionParams);
});​

functionParams将是一个包含您的值的数组。这可能是你需要的,也可能不是。你也可以像这样使用邪恶的eval

$(".button1").click(function() {
    eval($(this).attr("data-meth"));
});​

在这种情况下,您可以传入参数并像往常一样处理它们。