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

标签 jquery html

我正在创建一个网页,其中有 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/

相关文章:

javascript - 如何使用 jQuery 用动态生成的元素包装页面元素?

javascript - 选择 parent 的第二个 sibling

html - selectInput 选择显示标签中 Shiny 的额外空白

html - 如何让不同高度的html div float 起来

java - 带有 HTML 的 JtextPane 太宽

Jquery 数据表 dataTables_length

javascript - 对 S3 下载的图像的 URI 进行编码

javascript - HTML5 音频标签/mediaelement.js 的加载指示器

html - 尝试使用 HTML 和 CSS 在文本右侧对齐图像

javascript - 用于显示图像的简单 jquery 灯箱