如何获取元素点击(整个文档)? [英] 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
,这是最初触发事件的元素。您的示例代码中的此
指的是文档
。
在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 || text.innerText;
}, false);
另外,确保您是否需要支持< IE9,您使用 attachEvent()
而不是 addEventListener()
。
Also, ensure if you need to support < IE9 that you use attachEvent()
instead of addEventListener()
.
这篇关于如何获取元素点击(整个文档)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!