我要转这个
<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/