目前,我有一个<p>
处理过的匹配字,由<span class="matched">
包裹。
你好,今天过得怎么样?
.matched{
font-weight: bold;
}
<p>Hello, <span class="matched">how</span> is your <span class="matched">day</span><span class="matched"> today</span>?</p>
到
.matched{
font-weight: bold;
}
<p>Hello,
<span class="matched">how</span> is your <span class="matched">day today</span>?</p>
如何,天和今天这个词是<span class="matched">
中包含的匹配词,我该如何合并?一个<span class="matched">
标记,当它的下一个html元素也有<span class="matched">
成一个单独的''时?
非常感谢你们〜=)
编辑:这不会改变结果,但我希望我的来源看起来更好。
答案 0 :(得分:2)
以下是一种方法。请注意,我使用了标准DOM属性.nextSibling
和.nodeType
,因为对于这个问题,您必须考虑文本节点,但jQuery DOM导航方法往往会跳过文本节点。
var matchedArr = $("span.matched").get() // Select all .matched as array
var $current, next, $next
while (matchedArr.length > 0 ) { // While there are unprocessed ones left
current = matchedArr.shift() // Take from front of array
while(next = current.nextSibling) { // While that element has a next sibling
if (next.nodeType === 1) { // that is an element (not a text node)
var $next = $(next) // get next as jQuery object
if ($next.is("span.matched")) { // check if it has the class
// Add to the HTML of the current element
// (don't use .append() or you'll add separate text nodes):
$(current).html(function(i, content) { return content + $next.remove().html() })
matchedArr.shift() // remove *next* element from start of array so
// that it won't be processed separately
continue // continue inner loop to check for more siblings
}
}
break // break inner loop because the next sibling didn't match
}
}
// check results:
$("p").each(function() { console.log(this.innerHTML) })
.matched{
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Hello, <span class="matched">how</span> is your <span class="matched">day</span><span class="matched"> today</span>?</p>
<p>A test where <span class="matched">several</span><span class="matched"> elements</span><span class="matched"> in</span><span class="matched"> a</span><span class="matched"> row</span> have the class, but also <span class="matched">some</span><span> have</span> non-matching elements <span class="matched">after</span><span class="matched"> them</span>.</p>
请注意,内部循环中matchedArr.shift()
之前的行上的continue
是因为此时数组中的第一个元素是我们刚刚合并到{{1}的下一个兄弟所以我们current
该元素从数组中出来,这样我们就不会尝试在外部循环的下一次迭代中处理它。 (请注意,.shift()
按照文档中出现的顺序选择元素。)