首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >检查脚本标记中的内容

检查脚本标记中的内容
EN

Stack Overflow用户
提问于 2020-01-20 14:49:19
回答 1查看 55关注 0票数 1

我已经使用jquery为所有逗号添加了span标签,以便为css添加类。不幸的是,它在脚本中添加了span标签并被折叠。我想检查内容不在脚本标签中,并添加span标签。我想替换除脚本标签中的内容之外的所有逗号(,)。

代码语言:javascript
运行
复制
if ($("#overview").length > 0) {
   $("#overview").html( $("#overview").html().replace(/,/g,"<span class='comma'>,</span>")); 
}
EN

回答 1

Stack Overflow用户

发布于 2020-01-21 06:29:40

您需要小心,因为html属性也可以包含带有'‘的文本。

解决此问题的一种方法是通过TextNodes进行迭代,并为每个迭代拆分由SpanNode分隔的multiples TextNodes中的值。

代码语言:javascript
运行
复制
// get all text nodes excluding the script
function getTextNodes(el) {
  if (el.nodeType == 3) {  // nodeType 3 is a TextNode
    return el.parentElement && el.parentElement.nodeName == "SCRIPT" ? [] : [el];
  }
  return Array.from(el.childNodes)
    .reduce((acc, item) => acc.concat(getTextNodes(item)), []);
}

// this will replace the TextNode with the necessary Span and Texts nodes
function replaceComma(textNode) {
  const parent = textNode.parentElement;
  const subTexts = textNode.textContent.split(',');  // get all the subtexts separated by ,

  // for each item in subtext it will insert a new TextNode with a SpanNode
  // (iterate from end to beginning to use the insertBefore function)
  textNode.textContent = subTexts[subTexts.length - 1];
  let currentNode = textNode;
  for(var i = subTexts.length - 2;  i>= 0 ; i --) {
    const spanEl = createCommaEl();
    parent.insertBefore(spanEl, currentNode);
    currentNode = document.createTextNode(subTexts[i]);
    parent.insertBefore(currentNode, spanEl)
  }
}

// create the html node: <span class="comma">,</span>
// you can do this more easy with JQUERY
function createCommaEl() {
  const spanEl = document.createElement('span');
  spanEl.setAttribute('class', 'comma');
  spanEl.textContent = ',';
  return spanEl;
}

// then, if you want to replace all comma text from the element with id 'myId'
// you can do
getTextNodes(document.getElementById('myId'))
  .forEach(replaceComma);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59818213

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档