我想获取我单击的HTML文档中的当前元素(无论是什么元素)。我在用:
$(document).click(function () {
alert($(this).text());
});
但非常奇怪的是,我得到了整个(!)文档的文本,而不是单击的元素。
如何只获得我点击的元素?
<body>
<div class="myclass">test</div>
<p>asdfasfasf</p>
</body>
如果我点击“测试”文本,我希望能够在jQuery中使用$(this).attr("myclass"
读取属性。
你需要使用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。
在body标签内使用以下内容
<body onclick="theFunction(event)">
然后在javascript中使用以下函数来获取ID
<script>
function theFunction(e)
{ alert(e.target.id);}
window.onclick = e => {
console.log(e.target);
console.log(e.target.tagName);
}
从clicked元素中获取文本
window.onclick = e => {
console.log(e.target.innerText);
}
你可以在event.target
找到目标元素:
$(document).click(function(event) {
console.log($(event.target).text());
});
参考文献:
使用delegate
和event.target
。 delegate
通过让一个元素监听和处理子元素上的事件来利用事件冒泡。 target
是event
对象的jQ标准化属性,表示事件源自的对象。
$(document).delegate('*', 'click', function (event) {
// event.target is the element
// $(event.target).text() gets its text
});
但是:ぁzxswい
这是一个使用jQuery选择器的解决方案,因此您可以轻松定位任何类,ID,类型等的标记。
$(document).click(function (e) {
alert($(e.target).text());
});