jQuery 使用jquery在按钮点击时获取元素的id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2864327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get id of element on button click using jquery
提问by Xulfee
i have list of dynamic generated buttons and id is generated on run time. how can is get id of clicked button using JQuery.
我有动态生成的按钮列表,id 是在运行时生成的。如何使用 JQuery 获取单击按钮的 id。
Here is js code
这是js代码
var btn = " <input type='button' id='btnDel' value='Delete' />";
$("#metainfo").append(txt); //set value of
$("#btnDel").attr("id", "btnDel" + $("#hid").attr("value"));
回答by Nick Craver
For your example it would be like this:
对于您的示例,它会是这样的:
$("#btnDel").click(function() {
alert(this.id);
});
Note that you can't loop the code you have, IDs have to be unique, you'll get all sorts of side-effects if they're not, as it's invalid HTML. If you wanted a click handler for any input, change the selector, like this:
请注意,您不能循环您拥有的代码,ID必须是唯一的,如果不是,您将获得各种副作用,因为它是无效的 HTML。如果您想要任何输入的点击处理程序,请更改选择器,如下所示:
$("input").click(function() {
alert(this.id);
});
回答by Jan Willem B
$('.generatedButton').click(function() {
alert(this.id);
});
EDIT after you posted the code:
发布代码后编辑:
var btn =
$("<input type='button' value='Delete' />")
.attr("id", "btnDel" + $("#hid").val())
.click(function() {
alert(this.id);
});
$("body").append(btn);
回答by Siyavash Hamdi
You should add click event of the button after document is ready(Loaded):
您应该在文档准备好(加载)后添加按钮的单击事件:
$(document).ready(function(){
$("#btnDel").click(function() {
alert('Button clicked.');
});
});