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

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

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

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

例子

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

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


当前回答

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

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

引用:

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

其他回答

我知道这篇文章真的很旧了,但是,为了获得一个元素的内容,引用它的ID,这是我要做的:

window.onclick = e => {
    console.log(e.target);
    console.log(e.target.id, ' -->', e.target.innerHTML);
}

在body标签中使用以下代码

<body onclick="theFunction(event)">

然后在javascript中使用下面的函数来获取ID

<script>
function theFunction(e)
{ alert(e.target.id);}

调用函数时传递"this"作为参数:

< script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js " > < /脚本> < span onclick = " click_here(这个);“>点击< / span > <脚本> 函数click_here (elmnt) { 警报($ (elmnt)。text ()); } > < /脚本

事件。目标来获取元素

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);
} 

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

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

引用:

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