How to get the id of the element clicked using jQuery

*爱你&永不变心* 提交于 2019-11-26 10:53:23

问题


<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.

How the get the id of the span when clicked? How to do this using jQuery?


回答1:


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

$('span').on('click', function () {
    alert(this.id);
});

this refers to current span element clicked

this.id will give the id of the current span clicked




回答2:


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.

$(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

Direct vs. Delegated - jQuery .on()




回答3:


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");



回答4:


You can get the id of clicked one by this code

$("span").on("click",function(e){
    console.log(e.target.Id);
});

Use .on() event for future compatibility



来源:https://stackoverflow.com/questions/18680735/how-to-get-the-id-of-the-element-clicked-using-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!