如何点击元素(对于整个文档)? [英] How to get the element clicked (for the whole document)?
问题描述
我想获取我单击的 HTML 文档中的当前元素(无论是什么元素).我正在使用:
I would like to get the current element (whatever element that is) in an HTML document that I clicked. I am using:
$(document).click(function () {
alert($(this).text());
});
但很奇怪,我得到了整个(!)文档的文本,而不是被点击的元素.
But very strangely, I get the text of the whole(!) document, not the clicked element.
如何只获取我点击的元素?
How to get only the element I clicked on?
<body>
<div class="myclass">test</div>
<p>asdfasfasf</p>
</body>
如果我点击测试"文本,我希望能够在 jQuery 中使用 $(this).attr("myclass"
) 读取属性.
If I click on the "test" text, I would like to be able to read the attribute with $(this).attr("myclass"
) in jQuery.
推荐答案
你需要使用event.target
是最初触发事件的元素.示例代码中的 this
指的是 document
.
You need to use the event.target
which is the element which originally triggered the event. The this
in your example code refers to document
.
在 jQuery 中,这是...
In jQuery, that's...
$(document).click(function(event) {
var text = $(event.target).text();
});
没有 jQuery...
Without jQuery...
document.addEventListener('click', function(e) {
e = e || window.event;
var target = e.target || e.srcElement,
text = target.textContent || target.innerText;
}, false);
另外,请确保您是否需要支持 <您使用 attachEvent()
而不是 addEventListener()
的 IE9.
Also, ensure if you need to support < IE9 that you use attachEvent()
instead of addEventListener()
.
这篇关于如何点击元素(对于整个文档)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!