jquery - 使用 JavaScript/JQuery 替换元素之前的文本部分

标签 jquery dom

我有一个给定的文本,在一些单词之前带有 t 标签。 t 标签内部是标签之前单词的 id,我必须找到它并用一些 html 代码替换。到目前为止,我所拥有的似乎太复杂了,而且也不起作用,因为替换的 html 被打印为文本而不是 html。

有人有更好、更简单、更有效的解决方案吗?

JSFiddle:https://jsfiddle.net/fsdx2o7h/18/

This is the first<t>element1</t>. This is the second<t>element2</t>. This is the third<t>element3</t>.

$('t').each(function() {
        var prevText = this.previousSibling.nodeValue;
        var arrPrevText = prevText.split(' ');
        var nrElements = arrPrevText.length;
        var textpart = arrPrevText[nrElements-1];
        var id = $(this).html();
        arrPrevText[nrElements-1] = "<span id='" + id + "'>" + textpart + "</span>";
        this.previousSibling.nodeValue = arrPrevText.join(' ');
    });

最佳答案

是的,它可以更简单一些,但你走在正确的轨道上。查看评论:

$('t').each(function() {
  // Get our previous sibling
  var prev = this.previousSibling;
  // If not a text node, quit
  if (prev.nodeType !== 3) {
    return;
  }
  // Get the text of it
  var text = prev.nodeValue;
  // Find the last word; if none, quit
  var index = text.lastIndexOf(" ");
  if (index < 0){
    return;
  }
  // Skip past the space prior to the word
  ++index;
  // Grab the word
  var word = text.substring(index).trim();
  // Remove it from the text node
  prev.nodeValue = text.substring(0, index);
  // Replace this `t` element with a span using
  // the word as its text and this `t` element's
  // innerHTML as its ID
  $(this).replaceWith(
    $("<span>").text(word).attr("id", this.innerHTML)
  );
});
span[id] {
  color: red;
}
This is the first<t>element1</t>. This is the second<t>element2</t>. This is the third<t>element3</t>.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于jquery - 使用 JavaScript/JQuery 替换元素之前的文本部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39975892/

相关文章:

javascript - Ajax请求表单提交问题

javascript - 如何使用 jQuery 定义函数参数

javascript - 为什么用户选中一个框与以编程方式执行不同?

javascript - 使用 React refs 的 scrollIntoView

javascript - 卸载,还是隐藏在 React 中?

php - PHP-返回所有段落直到第一个<h2>

jquery - IE11 的 CORS 请求

javascript - 需要双击复选框进行勾选

具有多个元素的 Javascript document.getElementById()

javascript - 根据是/否将 Controller 中的项目保存到数组中