jQuery 如何使用jQuery获取点击的元素的id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18680735/
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
How to get the id of the element clicked using jQuery
提问by Gourav
<div class="main_div">
<div id="inner_div">
<span id="d1" class="get_clicked">click to get id</span>
</div>
</div>
How to get the id of the clicked element? The span which is present inside the inner_div will be having different ids because I will be loading the span from the model(MVC) using jquery ajax. So there will be 'n' number of span. All the span will have unique id. I want to get the id of the span which I click.
如何获取被点击元素的id?存在于inner_div 中的跨度将具有不同的ID,因为我将使用jquery ajax 从模型(MVC)加载跨度。所以会有'n'个跨度。所有跨度都将具有唯一 ID。我想获取我单击的跨度的 id。
How the get the id of the span when clicked? How to do this using jQuery?
单击时如何获取跨度的 id?如何使用 jQuery 做到这一点?
回答by Tushar Gupta - curioustushar
update as you loading contents dynamically so you use.
动态加载内容时更新,以便您使用。
$(document).on('click', 'span', function () {
alert(this.id);
});
old code
旧代码
$('span').click(function(){
alert(this.id);
});
or you can use .on
或者你可以使用.on
$('span').on('click', function () {
alert(this.id);
});
this
refers to current span element clicked
this
指当前点击的跨度元素
this.id
will give the id
of the current span clicked
this.id
将给出id
单击的当前跨度的
回答by DGS
Since you are loading in the spans via ajax you will have to attach delegate handlers to the events to catch them as they bubble up.
由于您通过 ajax 加载跨度,因此您必须将委托处理程序附加到事件以在它们冒泡时捕获它们。
$(document).on('click','span',function(e){
console.log(e.target.id)
})
you will want to attach the event to the closest static member you can to increase efficiency.
您需要将事件附加到最近的静态成员以提高效率。
$('#main_div').on('click','span',function(e){
console.log(e.target.id)
})
is better than binding to the document for instance.
例如,比绑定到文档更好。
This question may help you understand
这个问题可以帮助你理解
回答by frankenapps
I wanted to share how you can use this to change a attribute of the button, because it took me some time to figure it out...
我想分享如何使用它来更改按钮的属性,因为我花了一些时间才弄明白...
For example in order to change it's background to yellow:
例如,为了将其背景更改为黄色:
$("#"+String(this.id)).css("background-color","yellow");
回答by Hemal
You can get the id of clicked one by this code
您可以通过此代码获取点击的 ID
$("span").on("click",function(e){
console.log(e.target.Id);
});
Use .on()
event for future compatibility
使用.on()
事件以实现未来兼容性