use*_*216 125 html javascript jquery dom
我想获取我单击的HTML文档中的当前元素(无论是什么元素).我在用:
$(document).click(function () {
alert($(this).text());
});
Run Code Online (Sandbox Code Playgroud)
但非常奇怪的是,我得到了整个(!)文档的文本,而不是单击的元素.
如何只获得我点击的元素?
<body>
<div class="myclass">test</div>
<p>asdfasfasf</p>
</body>
Run Code Online (Sandbox Code Playgroud)
如果我点击"测试"文本,我希望能够$(this).attr("myclass"
在jQuery中读取属性.
ale*_*lex 207
您需要使用event.target
最初触发事件的元素.在this
您的示例代码指document
.
在jQuery中,那是......
$(document).click(function(event) {
var text = $(event.target).text();
});
Run Code Online (Sandbox Code Playgroud)
没有jQuery ......
document.addEventListener('click', function(e) {
e = e || window.event;
var target = e.target || e.srcElement,
text = target.textContent || target.innerText;
}, false);
Run Code Online (Sandbox Code Playgroud)
此外,请确保您是否需要支持使用的<IE9 attachEvent()
而不是addEventListener()
.
bhv*_*bhv 18
window.onclick = e => {
console.log(e.target);
console.log(e.target.tagName);
}
Run Code Online (Sandbox Code Playgroud)
从clicked元素中获取文本
window.onclick = e => {
console.log(e.target.innerText);
}
Run Code Online (Sandbox Code Playgroud)
Mal*_*aht 17
在body标签内使用以下内容
<body onclick="theFunction(event)">
Run Code Online (Sandbox Code Playgroud)
然后在javascript中使用以下函数来获取ID
<script>
function theFunction(e)
{ alert(e.target.id);}
Run Code Online (Sandbox Code Playgroud)
您可以在event.target
以下位置找到目标元素:
$(document).click(function(event) {
console.log($(event.target).text());
});
Run Code Online (Sandbox Code Playgroud)
参考文献: