简体   繁体   English

当单击特定ID中的按钮元素时,jQuery调用函数

[英]jquery call a function when button element in a specific id is clicked

I would like to call a function when any button is pressed within a particular table. 我想在特定表格中按下任何按钮时调用一个函数。

This works to call the function when any button is pressed anywhere 当在任何地方按下任何按钮时,可以调用该函数

$(document)
  .on('click', 'button', fuction(){
   ...
  });

But I would like it to do it in a more specific case. 但我希望它能在更具体的情况下进行。

$(document)
  .on('click', '#imgPreviewTable.button', function(){
    ...     
  });

I know I can set the buttons to call a function independently but I need to do it this way. 我知道我可以设置按钮来独立调用函数,但是我需要这样做。 Any help is appreciated. 任何帮助表示赞赏。

here is an example 这是一个例子

HTML CODE: HTML代码:

<table id="mytable">
<thead>
<tr><th>Buttons</th></tr>
</thead>
<tbody>
<tr><td><input type="button" class="Tblbutton" value="button 1"></td></tr>
<tr><td><input type="button" class="Tblbutton" value="button 2"></td></tr>
<tr><td><input type="button" class="Tblbutton" value="button 3"></td></tr>
</tbody>
</table>

Javascript Code JavaScript代码

$('#mytable Tblbutton').on('click',function(){
alert($(this).val());
})

Result is it would alert the value of the button you have clicked 结果是它将警告您单击的按钮的值

Just a little addition, when buttons are created dynamically (with js). 只需一点点,即可动态创建按钮(使用js)。 The above shown examples won´t work. 上面显示的示例不起作用。

$('#imgPreviewTable').on('click', 'button', function(){
    // do something
})

http://api.jquery.com/on/ http://api.jquery.com/on/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM