2015-09-27 16 views
2

我希望把這個的Javascript,jQuery的:改變一個div的某個詞爲<span>與函數

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

成這樣:

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

使用此項功能:

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

所以該函數將搜索元素wi中的searchedWord(在這種情況下爲potatoes) th id wrapId(在這種情況下爲#theDiv),並將其替換爲span,其編號爲"#" + searchedWord + "Span"

我該怎麼辦?我有一些呈現給我的方法,看起來太複雜了,這就是我在這裏問的原因。

+0

有沒有考慮過,也許尋找像你這樣的,然後朝着一側DIV中新創建的跨度的內容,並刪除原始div標記? – TrojanMorse

回答

1

您可以使用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>

+0

在這種情況下覆蓋HTML並不是很好的方法。 – dfsq

+0

@dfsq:更新了答案.. –