我想在我点击的HTML文档中获得当前元素(无论那是什么元素)。我正在使用:

$(document).click(function () {
    alert($(this).text());
});

但非常奇怪的是,我得到的是整个(!)文档的文本,而不是单击的元素。

如何只得到我点击的元素?

例子

<body>
    <div class="myclass">test</div>
    <p>asdfasfasf</p>
</body>

如果我点击“测试”文本,我希望能够阅读属性与jQuery $(this).attr(“myclass”)。


当前回答

事件。目标来获取元素

window.onclick = e => {
    console.log(e.target);  // to get the element
    console.log(e.target.tagName);  // to get the element tag name alone
} 

从单击的元素中获取文本

window.onclick = e => {
    console.log(e.target.innerText);
} 

其他回答

使用delegate和event.target。委托通过让一个元素监听并处理子元素上的事件来利用事件冒泡。target是事件对象的jq规范化属性,表示事件起源于的对象。

$(document).delegate('*', 'click', function (event) {
    // event.target is the element
    // $(event.target).text() gets its text
});

演示:http://jsfiddle.net/xXTbP/

事件。目标来获取元素

window.onclick = e => {
    console.log(e.target);  // to get the element
    console.log(e.target.tagName);  // to get the element tag name alone
} 

从单击的元素中获取文本

window.onclick = e => {
    console.log(e.target.innerText);
} 
$(document).click(function (e) {
    alert($(e.target).text());
});

这是javascript中最简单的获取点击元素的方式。

window.addEventListener('click', (e) => console.log(e.target));

你可以在event.target中找到目标元素:

$(document).click(function(event) {
    console.log($(event.target).text());
});

引用:

http://api.jquery.com/event.target/