简体   繁体   中英

jQuery attr('id') is returning 'undefined'

html:

<button class="btn" id="1"></button>
<p></p>

jquery:

$('.btn').click(function() {
    var id=$(this).attr('id');
    $('p').html(id);
});

Returns:

undefined

This question is Corrected

$(this)

In this case I suggest you to use $(this)

 $('button').click(function(){ console.log($(this).attr("id")); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="btn" id="150">Click Me</button> 


event.target

Also as @aspiring_dev mentioned in his answer you can use the event argument of jQuery handler function in the click function:

 $('.btn').click(function(event){ console.log($(event.target).attr('id')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="btn" id="1">Button</button> <p></p> 


Different between $(this) and event.target

I wrote a click event for div in the following example. now click on the Button 1 , Button 2 and yellow div to see the different between results. event.target is equal the child clicked element but this always is equal div .

 $('div').click(function(event){ var thisId = $(this).attr('id'); var eventTargetId = $(event.target).attr('id'); console.log('thisId » ' + thisId); if(eventTargetId.indexOf('mainDiv')<0) console.log('eventTargetId » ' + eventTargetId); else console.log('eventTargetId' +' = '+ 'thisId » ' + thisId ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mainDiv" style="padding:20px;background:#fdd800;border:1px solid orange;"> <button class="btn1" id="btn1">Button 1</button> <button class="btn2" id="btn2">Button 2</button> </div> 


window.event.target

在此处输入图片说明

在此处输入图片说明

event.target is already available in IE9+ . If you need to support IE6-8 , then event.srcElement needs to be used.

 $('button').click(function(){ console.log($(window.event.target).attr("id")); console.log($(window.event.srcElement).attr("id")); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="btn" id="150">Click Me</button> 

event is not defined in the callback, try something like this

 $('.btn').click(function(event) { // you're not passing `event` so it's undefined var id=$(event.target).attr('id'); $('p').html(id); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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