我正在创建一个网页,其中有 3 个元素,每个元素都有自己的 ID,在脚本部分,我有 3 个与 html ID 同名的函数。我想在单击元素时执行相应的函数。以下是我的代码:( fiddle )
HTML:
<div id="one" class="btn">
Click here for 1
</div>
<div id="two" class="btn">
Click Here for 2
</div>
<div id="three" class="btn">
Click Here for 3
</div>
JQ:
$('.btn').on('click',function(){
$(this).attr('id')() //here I want to run function
});
function one(){alert("one clicked")}
function two(){alert("two clicked")}
function three(){alert("three clicked")}
请帮忙..我不想使用 if 语句...我正在尝试以最优化的方式执行此操作.. :) 这是fiddle的链接
最佳答案
将函数定义为一个对象,如下所示,
var myFunc = {
one: function (){alert("one clicked")},
two: function (){alert("two clicked")},
three: function (){alert("three clicked")}
};
现在在处理程序内部调用,
myFunc[this.id](); //Note: this.id is good and better than $(this).attr('id')
关于jquery - 根据 html 元素 ID 的名称执行 JQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17348431/