根据html元素ID的名称执行JQuery函数

Bha*_*oni 2 html jquery

我正在创建一个网页,其中有3个元素,每个都有自己的ID,在脚本部分我有3个与html ID同名的函数..我想在点击元素时执行各自的功能..以下是我的代码:( 小提琴)

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>
Run Code Online (Sandbox Code Playgroud)

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")}
Run Code Online (Sandbox Code Playgroud)

请帮助..我不想使用if语句...我试图以最优化的方式做到这一点.. :)这里是小提琴的链接

Sel*_*gam 10

将函数定义为对象,如下所示,

var myFunc = {
  one: function (){alert("one clicked")},
  two: function (){alert("two clicked")},
  three: function (){alert("three clicked")}
};
Run Code Online (Sandbox Code Playgroud)

现在调用处理程序内部,

myFunc[this.id](); //Note: this.id is good and better than $(this).attr('id')
Run Code Online (Sandbox Code Playgroud)