Проверьте содержимое в теге скрипта - PullRequest
1 голос
/ 20 января 2020

Я добавил тег span для всех запятых, используя jquery, чтобы добавить класс для css. к сожалению, он добавляет тэг span внутри скрипта и становится свернутым. Я хочу проверить, что содержимое отсутствует в тэге скрипта, и добавить тэг span. Я хочу заменить все запятые (,), кроме содержимого в тэге скрипта.

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

1 Ответ

0 голосов
/ 21 января 2020

Вы должны быть осторожны, потому что атрибуты html также могут содержать текст с , .

Один из способов решить эту проблему - выполнить итерацию с помощью TextNodes, и для каждого из них значение делится на несколько 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...