使用javaScript函数onclick div替换HTML内容?

时间:2018-07-17 05:42:56

标签: javascript html

我有下面的代码片段,它将输出 HTML ,但是我希望文本 A0100 A0102 作为组合字符串

function closespan(val) {
  var parent = val.parentElement;
  parent.parentElement.removeChild(parent);
  var valHTML = document.getElementById("lblshowselected").innerHTML;
  var valSPLIT = valHTML.replace(/<img src="images\/delete.png" height="10">/, ",");
  var valTEXT = valSPLIT.innerText;
}
<div runat="server" id="lblshowselected">
  <div class="tknz-token">A0100<span class="tknz-token-x" onclick="closespan(this);"><img src="images/delete.png" height="10"></span></div>
  <div class="tknz-token">A0102<span class="tknz-token-x" onclick="closespan(this);"><img src="images/delete.png" height="10"></span></div>
</div>

输出
valHTML:"<div class="tknz-token">A0100<span class="tknz-token-x" onclick="closespan(this);"><img src="images/delete.png" height="10"></span></div><div class="tknz-token">A0102<span class="tknz-token-x" onclick="closespan(this);"><img src="images/delete.png" height="10"></span></div>"

预期输出

  

A0100,A0102

2 个答案:

答案 0 :(得分:4)

您需要使用tknz-token获取getElementsByClassName()元素,并迭代以在数组中获取推送textContent

这里是一个例子,我只添加了代码来获取textContent

function closespan(val) {
  //Modified code
  var lbl = document.getElementById("lblshowselected");
  var arr = [];
  var tokens = lbl.getElementsByClassName('tknz-token');
  for (var i = 0; i < tokens.length; i++) {
    arr.push(tokens[i].textContent);
  }
  console.log(arr.join(','));
}
<div runat="server" id="lblshowselected">
  <div class="tknz-token">A0100<span class="tknz-token-x" onclick="closespan(this);"><img src="images/delete.png" height="10"></span></div>
  <div class="tknz-token">A0102<span class="tknz-token-x" onclick="closespan(this);"><img src="images/delete.png" height="10"></span></div>
</div>

答案 1 :(得分:1)

将您的文本添加为​​HTML,而不是普通文本

function closespan(val) {
  debugger;
  var parent = val.parentElement;
  parent.parentElement.removeChild(parent);
  var valHTML = document.getElementById("lblshowselected");
  var valSPLIT = valHTML.replace(/<img src="images\/delete.png" height="10">/, ",");
  valHTML.innerHTML(valSPLIT);
}
<div runat="server" id="lblshowselected">
  <div class="tknz-token">A0100<span class="tknz-token-x" onclick="closespan(this);"><img src="images/delete.png" height="10"></span></div>
  <div class="tknz-token">A0102<span class="tknz-token-x" onclick="closespan(this);"><img src="images/delete.png" height="10"></span></div>
</div>