不寻常的情况。我有一个客户,我们称之为“BuyNow”。他们希望在网站内容中出现的每个实例中,将他们的名称样式化为“BuyNow”,其中他们名称的后半部分为粗体。
我真的不想花一整天时间为所有内容添加标签。有没有一种使用jQuery的好方法来做到这一点?
我已经看到了jQuery的高亮插件,它非常接近,但我需要将单词的第二个部分加粗。
不寻常的情况。我有一个客户,我们称之为“BuyNow”。他们希望在网站内容中出现的每个实例中,将他们的名称样式化为“BuyNow”,其中他们名称的后半部分为粗体。
我真的不想花一整天时间为所有内容添加标签。有没有一种使用jQuery的好方法来做到这一点?
我已经看到了jQuery的高亮插件,它非常接近,但我需要将单词的第二个部分加粗。
// Find text in descendents of an element, in reverse document order
// pattern must be a regexp with global flag
//
function findText(element, pattern, callback) {
for (var childi= element.childNodes.length; childi-->0;) {
var child= element.childNodes[childi];
if (child.nodeType==1) {
findText(child, pattern, callback);
} else if (child.nodeType==3) {
var matches= [];
var match;
while (match= pattern.exec(child.data))
matches.push(match);
for (var i= matches.length; i-->0;)
callback.call(window, child, matches[i]);
}
}
}
findText(document.body, /\bBuyNow\b/g, function(node, match) {
var span= document.createElement('span');
span.className= 'highlight';
node.splitText(match.index+6);
span.appendChild(node.splitText(match.index+3));
node.parentNode.insertBefore(span, node.nextSibling);
});
replace()
函数是常见的编程工具。例如:var text = $([selector]).html();
text = text.replace(/Now/g,'<strong>Now<\strong>');
$([selector]).html(text);
html()
来实现这一点需要注意。首先,有可能会替换<a>
元素的href
属性和其他属性中匹配的字符串,从而导致页面功能不正确。也许可以编写更好的正则表达式来克服一些潜在的问题,但性能可能会受到影响(我不是正则表达式专家)。其次,使用html()
来替换内容将导致非可序列化数据(例如绑定到元素标记、表单数据等的事件处理程序)丢失。编写一个只针对文本节点的函数可能是更好/更安全的选择,这取决于页面的复杂程度。按照SingleShot的建议,使用带有CSS类的<span>
比使用<strong>
元素更加灵活。
<a href="BuyNow.html">
-> 哎呀。 - bobincehtml()
会丢失所有不可序列化的信息,例如事件处理程序、JavaScript 引用和表单数据。 - bobincevar elem = $([selector]); elem.html(elem.html().replace(/Now/g,'<strong>Now<\strong>'));
- Gumbovar Run=Run || {};
Run.makestrong= function(hoo, Rx){
if(hoo.data){
var X= document.createElement('strong');
X.style.color= 'red'; // testing only, easier to spot changes
var pa= hoo.parentNode;
var res, el, tem;
var str= hoo.data;
while(str && (res= Rx.exec(str))!= null){
var tem= res[1];
el= X.cloneNode(true);
el.appendChild(document.createTextNode(tem));
hoo.replaceData(res.index, tem.length,'');
hoo= hoo.splitText(res.index);
str= hoo.data;
if(str) pa.insertBefore(el, hoo);
else{
pa.appendChild(el);
return;
}
}
}
}
Run.godeep= function(hoo, fun, arg){
var A= [];
if(hoo){
hoo= hoo.firstChild;
while(hoo!= null){
if(hoo.nodeType== 3){
if(hoo.data) A[A.length]= fun(hoo, arg);
}
else A= A.concat(arguments.callee(hoo, fun, arg));
hoo= hoo.nextSibling;
}
}
return A;
}
//test
**Run.godeep(document.body, Run.makestrong,/([Ee]+)/g);**
<span>
标签会更加合适。 - bobince