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

时间:2018-03-23 08:54:41

标签: javascript html

屏幕上有html,看起来像这样。

屏幕:

target1 target2 target3 target4

代码:

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

当我点击target4时 我想得到文字&#34; target4&#34;

你如何接近它?

3 个答案:

答案 0 :(得分:1)

您可以获取上一个文本节点的值,这不是问题。不幸的是:

  

childNodes may include text nodes, which don't support event handlers

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>

答案 1 :(得分:1)

这回答了你的两个问题

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>

答案 2 :(得分:0)

scraaapy已回答你的问题。但是如果您可以控制HTML,那么就这样做:

HTML

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

的JavaScript

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

这样,您的代码更易于维护和使用。希望这有帮助!