如何点击元素(对于整个文档)?

问题描述 投票:109回答:7

我想获取我单击的HTML文档中的当前元素(无论是什么元素)。我在用:

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

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

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

Example

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

如果我点击“测试”文本,我希望能够在jQuery中使用$(this).attr("myclass"读取属性。

javascript jquery html dom
7个回答
190
投票

你需要使用event.target,它是最初触发事件的元素。示例代码中的this指的是document

在jQuery中,那是......

$(document).click(function(event) {
    var text = $(event.target).text();
});

没有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。


16
投票

在body标签内使用以下内容

<body onclick="theFunction(event)">

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

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


11
投票
window.onclick = e => {
    console.log(e.target);
    console.log(e.target.tagName);
} 

从clicked元素中获取文本

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

5
投票

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

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

参考文献:


3
投票

使用delegateevent.targetdelegate通过让一个元素监听和处理子元素上的事件来利用事件冒泡。 targetevent对象的jQ标准化属性,表示事件源自的对象。

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

但是:ぁzxswい



-1
投票

这是一个使用jQuery选择器的解决方案,因此您可以轻松定位任何类,ID,类型等的标记。

$(document).click(function (e) {
    alert($(e.target).text());
});
© www.soinside.com 2019 - 2024. All rights reserved.