简体   繁体   English

如果文本不在html标记内,单击时如何获取文本值?

[英]How to get text values when click if text are not inside html tag?

There is html on the screen that looks like this. 屏幕上看起来像这样的html。

screen: 屏幕:

target1 target2 target3 target4

code: 码:

<div>
  target1
  <span>target2</span>
  <span>target3</span>
  target4
</div>

When i click on target4, I want to get the text "target4" 当我单击target4时,我想获得文本“ target4”

How do you approach it? 您如何处理?

you can get the value of your last text node, this is not a problem. 您可以获取最后一个文本节点的值,这不是问题。 Unfortunately : 不幸的是:

childNodes may include text nodes, which don't support event handlers childNodes可能包含不支持事件处理程序的文本节点

 var x = document.getElementsByTagName("div")[0]; x.addEventListener("click",function(e){ console.log(e.currentTarget.childNodes[4].textContent)}); 
 <div> target1 <span>target2</span> <span>target3</span> target4 </div> 

This answer both questions you had 这回答了你的两个问题

 var div = document.querySelector("div"); // get the div wrapper div.childNodes.forEach(function(node) { // loop over the nodes var text = node.textContent; // get the text if (node.nodeName=="#text" && text.trim()!="") { // if text and not empty var span = document.createElement("span"); // wrap in a span span.textContent = node.textContent.trim(); node = div.replaceChild(span,node); } }); div.onclick=function(e) { console.log(e.target.textContent); } 
 span { color:red } 
 <div> target1 <span>target2</span> <span>target3</span> target4 </div> 

scraaapy has answered your question. scraaapy回答了您的问题。 But if you have the control over the HTML, then just do this: 但是,如果您可以控制HTML,则只需执行以下操作:

HTML 的HTML

<div>
  <span>target1</span>
  <span>target2</span>
  <span>target3</span>
  <span>target4</span>
</div>

JavaScript 的JavaScript

var el = document.querySelector("div");
  el.addEventListener("click", (e) => {
  console.log(e.target.textContent);
});

This way, your code is much easier to maintain and work with. 这样,您的代码就更易于维护和使用。 Hope this help! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM