簡體   English   中英

如果文本不在html標記內,單擊時如何獲取文本值?

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

屏幕上看起來像這樣的html。

屏幕:

target1 target2 target3 target4

碼:

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

當我單擊target4時,我想獲得文本“ target4”

您如何處理?

您可以獲取最后一個文本節點的值,這不是問題。 不幸的是:

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> 

這回答了你的兩個問題

 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回答了您的問題。 但是,如果您可以控制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);
});

這樣,您的代碼就更易於維護和使用。 希望有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM