我正在创建一个网页,其中有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
的链接答案 0 :(得分:10)
将函数定义为如下对象
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')
答案 1 :(得分:3)
使用窗口全局对象的另一种方法:
$('.btn').on('click',function(){
window[this.id](); //here I want to run function
});
one = function(){alert("one clicked")}
two = function(){alert("two clicked")}
three = function(){alert("three clicked")}
答案 2 :(得分:1)
好的,试试这个:
var theFunctions = {
one: function () { alert("one clicked"); },
two: function () { alert("two clicked"); },
three: function () { alert("three clicked"); },
};
$('.btn').on('click',function(){
theFunctions[$(this).attr('id')](); //here I want to run function
});
答案 3 :(得分:0)
答案 4 :(得分:0)
$('.btn').on('click',function(){
eval($(this).attr('id'))();
});