jQuery:查找并包装包含某个元素的textnode
我的HTML代码:jQuery:查找并包装包含某个元素的textnode,jquery,textnode,Jquery,Textnode,我的HTML代码: <body>Firebrand will tend to burn any bricks out there. so the best idea is to ignore any active firebrand if you are a bricks. Otherwise, you can challenge a firebrand if you have the proper quality to keep up with their latest techn
<body>Firebrand will tend to burn any bricks out there. so the best idea is to ignore any active firebrand if you are a bricks. Otherwise, you can challenge a firebrand if you have the proper quality to keep up with their latest technology. And don't mess up with firebrand if you are a robber.</body>
我想找到身体内的任何火种,并使用jQuery将其替换为firebrand尝试以下操作
var textApply;
textApply = function(node){
jQuery.map($(node), function(node) {
var value = $(node)[0];
if (value.nodeType == 3 && value.textContent.match(/firebrand/gi)) {
var foo = value.textContent.replace(/[\n\r\t ]+/,' ').replace(/firebrand/gi, '<span style="color:red">Firebrand</span>');
var newitem = $(foo);
$(node).replaceWith(newitem);
} else if (value.nodeName != 'SCRIPT') {
jQuery.map($(node).contents(), textApply);
}
});
};
textApply($('body'));
试试下面的方法
var textApply;
textApply = function(node){
jQuery.map($(node), function(node) {
var value = $(node)[0];
if (value.nodeType == 3 && value.textContent.match(/firebrand/gi)) {
var foo = value.textContent.replace(/[\n\r\t ]+/,' ').replace(/firebrand/gi, '<span style="color:red">Firebrand</span>');
var newitem = $(foo);
$(node).replaceWith(newitem);
} else if (value.nodeName != 'SCRIPT') {
jQuery.map($(node).contents(), textApply);
}
});
};
textApply($('body'));
只需在DOM中递归,同时使用: .更换/firebrand/gi,“1美元” 在每个文本内容上
function firebrand($el) {
$el.contents().each(function () {
if (this.nodeType == 3) { // Text only
$(this).replaceWith($(this).text()
.replace(/(firebrand)/gi, '<span class="firebrand">$1</span>'));
} else { // Child element
firebrand($(this));
}
});
}
firebrand($("body"));
只需在DOM中递归,同时使用: .更换/firebrand/gi,“1美元” 在每个文本内容上
function firebrand($el) {
$el.contents().each(function () {
if (this.nodeType == 3) { // Text only
$(this).replaceWith($(this).text()
.replace(/(firebrand)/gi, '<span class="firebrand">$1</span>'));
} else { // Child element
firebrand($(this));
}
});
}
firebrand($("body"));
请更清楚地表达你的意图。正如您在Karim79的答案中所看到的,规范不够清晰。对不起,我的错,我只想找到希望用span包装的任何关键字,不管父元素是什么,它都应该在整个文档中搜索。我需要得到文本节点并用span将其包装起来,这样我就可以提供不同的样式。我是否可以不用$selector.html来完成这项工作?请更清楚地表达您的意图。正如您在Karim79的答案中所看到的,规范不够清晰。对不起,我的错,我只想找到希望用span包装的任何关键字,不管父元素是什么,它都应该在整个文档中搜索。我需要得到文本节点并用span将其包装起来,这样我就可以提供不同的样式。我是否可以不用$selector.html来完成这个任务?这帮我解决了!谢谢大家!+这帮我一把!谢谢大家!+1.