简体   繁体   English

Javascript,jQuery:将某个 div 的某个单词更改为<span>带有函数的 a</span>

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

I want to turn this我想转这个

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

into this:进入这个:

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

with this function:使用此功能:

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

So the function would search for the searchedWord (in this case potatoes ) in the element with the id wrapId (in this case #theDiv ) and replace it for a span with the id "#" + searchedWord + "Span" .因此,功能将搜索searchedWord (在这种情况下, potatoes与ID的元素) wrapId (在这种情况下#theDiv )和替换它的span id为"#" + searchedWord + "Span"

How can I do it?我该怎么做? I had some methods presented to me that seem way too complicated and that is why I'm asking here.我向我展示了一些看起来太复杂的方法,这就是我在这里问的原因。

You can use html() and replace() for that您可以为此使用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>

Update : The above solution cause several problems, that it will remove event handler from inner elements.更新:上述解决方案会导致几个问题,即会从内部元素中删除事件处理程序。 So you can do something like this, which only replace content in textNode所以你可以做这样的事情,它只替换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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM