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

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

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

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

例子

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

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


当前回答

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

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

其他回答

你可以在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);
}

下面是一个使用jQuery选择器的解决方案,这样你就可以轻松地瞄准任何类、ID、类型等标签。

jQuery('div').on('click', function(){
    var node = jQuery(this).get(0);
    var range = document.createRange();
    range.selectNodeContents( node );
    window.getSelection().removeAllRanges();
    window.getSelection().addRange( range );
});

调用函数时传递"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);
}