gpt4 book ai didi

javascript - 使用 'this' 单击页面时 jquery 获取元素 id 不起作用

转载 作者:行者123 更新时间:2023-11-28 16:27:03 24 4
gpt4 key购买 nike

我想在用户单击页面时获取页面上任何元素的 id。这里有几篇文章显示使用“this”有效,但我的代码不适用于“this”。返回的 id 未定义。但我使用“事件”技术并且它有效。

有人可以解释一下这些差异吗?

$(function(){

//document or 'body' tags both don't work

$('body').click(function(){

//var id = event.target.id;
var id=$(this).attr('id');
alert (id);
//returned undefined


});

});

此代码有效

$(function(){

$('body').click(function(event){

var id = event.target.id;
//var id=$(this).attr('id');
alert (id);



});});

最佳答案

使用下面的函数,变量id将引用body元素的id本身。

$('body').click(function() {
var id = $(this).attr('id');
alert(id); // Will alert "undefined" if the <body> tag has no id
});

使用像下面这样的不同函数实际上可以通过使用 event.target 来实现您想要的功能,这是 body 中实际单击的元素元素:

$('body').click(function(event) {    
var id = event.target.id;
alert(id); // Will alert the id if the element has one
});

所以,简而言之:event.target是被单击的元素,$(this)将指的是<body>标签。

关于javascript - 使用 'this' 单击页面时 jquery 获取元素 id 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7643274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com