Javascript,jQuery : Change a certain word of a div into a <span> with a function

标签 javascript jquery html

我要转这个

<div id='theDiv'>I love potatoes</div>

进入这个:

<div>I love <span id='potatoesSpan'>potatoes</span></div>

有了这个功能:

turnWordIntoSpan("#theDiv","potatoes");

因此该函数将在 ID 为 wrapId(在本例中为 #theDiv) 并将其替换为 ID 为 "#"+ searchedWord + "Span"span

我该怎么做?我收到了一些看起来太复杂的方法,这就是我在这里问的原因。

最佳答案

您可以为此使用html()replace()

function turnWordIntoSpan(id, replace) {
  $(id).html(function(i, v) {
    return v.replace(replace, "<span id='potatoesSpan'>$&</span>");
  })
}

turnWordIntoSpan("#theDiv", "potatoes");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='theDiv'>I love potatoes</div>

更新: 上述解决方案导致了几个问题,它将从内部元素中删除事件处理程序。所以你可以这样做,它只替换 textNode

中的内容

function turnWordIntoSpan(id, replace) {
  var add = 0;
  $(id).contents()
    // contents() for getting descentant including textnode
    .each(function(i) {
      // each() for iterating over elements
      if (this.nodeType === 3) {
        // checking node is textnode  
        var child = this;
        var parent = this.parentNode;
        // getting it's parent node
        var split = this.nodeValue.split(replace);
        // spliting string based on the replace parameter

        if (replace.length > 1) {
          split.forEach(function(v, ind) {
            // iterating over splited string
            if (ind == 0)
              child.nodeValue = v;
            else {
              var text = document.createTextNode(v);
              // creating textnode
              parent.insertBefore(text, child.nextSibling);
              // insering into parent
              child = text;
            }
            if (ind != split.length - 1) {
              var sp1 = document.createElement("span");
              // creating span
              sp1.style.color = 'red';
              sp1.innerHTML = replace;
              // setting span content
              parent.insertBefore(sp1, child.nextSibling);
              // insering span into parent node
              child = sp1;
            }
          });
        }
      }
    });
}

turnWordIntoSpan("#theDiv", "potatoes");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='theDiv'>I love potatoes hjhghgh potatoes bvbb <span>jhjghjj</span> potatoes hhhhh
  <div>jhjh</div>dhsjhdjshdjshj potatoes hgdhgh xcxcxcx</div>

关于Javascript,jQuery : Change a certain word of a div into a <span> with a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32806594/

相关文章:

html - 使用背景图片在两个元素之间绘制点

javascript - 显示属于同类型ID的Listview标记

javascript - 如何获取输入值并将其 append 到新元素?

javascript - useContext 仅适用于无状态功能组件

javascript - 欧芹远程无效返回 null

javascript - 处理来自多个元素的 Javascript 事件

html - Chrome 和 FF 之间的像素差异

javascript - 使用动态生成的对象数组填充 ember-power-select 时,无法将对象转换为 Array.toString( native )的原始值

javascript - 使用javascript测试文件是否存在

jquery - ul li attach 每次点击添加一个 openToggle 类