javascript - 检查script标签中的内容

标签 javascript jquery html

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

if ($("#overview").length > 0) {
   $("#overview").html( $("#overview").html().replace(/,/g,"<span class='comma'>,</span>")); 
}

最佳答案

您需要小心,因为 html 属性还可以包含带有“,”的文本。

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

// 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);

关于javascript - 检查script标签中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59818213/

相关文章:

javascript - 嵌入(iframe 或对象)和修改 (jQuery) 网页

html - 将背景图像与 DOCTYPE 一起使用

javascript - 如何在 JS 生成的内容上使用样式

javascript - 在发送交易之前如何估计当前的gas limit?

javascript - 解析未转义 XML 中的 unicode

javascript - 为什么我的脚本中多次触发点击事件?

jquery - 屏蔽视频 iframe 周围的边框

html - 响应式CSS显示网页的移动版本

javascript - 比较两个 json 数组并更改位置的最佳方法

javascript - 是否有可以用作库的 V8 CommonJS 实现?