html:
<button class="btn" id="1"></button>
<p></p>
jquery:
$('.btn').click(function() {
var id=$(this).attr('id');
$('p').html(id);
});
返回:
undefined
此问题已更正
最佳答案
$(这个)
在这种情况下,我建议您使用 $(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
正如@aspiring_dev在他的回答中提到的,您可以在click
函数中使用jQuery处理函数的事件参数:
$('.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>
$(this)
和 event.target
之间的不同
我在下面的例子中为div编写了一个点击事件。现在点击 Button 1
、 Button 2
和黄色 div
来查看结果之间的不同。 event.target
等于子点击元素,但 this
始终等于 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 inIE9+
. If you need to supportIE6-8
, thenevent.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>
关于javascript - jQuery attr ('id' )正在返回 'undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48475518/