有没有一种方法可以在jQuery中找到jQuery中的文本字符串,而不是用其他东西替换它,但是用一个元素包装该文本,这样当脚本完成时,它会用文本字符串包裹原始文本.
例:
原文
"Hello world to all people"
Run Code Online (Sandbox Code Playgroud)
搜索字符串
"world to"
Run Code Online (Sandbox Code Playgroud)
用...来代替 <i></i>
最终输出
"Hello <i>World to</i> all people"
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的帮助!
一种工作代码:
function highlightChild(child) {
$(childElements[child]).text("");
console.log(child);
$('.child_element_' + child).bind('textselect', function(e){
var selection = e.text;
var str = $("#construct_version").text();
var wrap = jQuery(childElements[child]).text(selection);
var re = new RegExp("" + selection + "", "g");
console.log(str.replace(selection, function(match, key, val){
console.log(match);
console.log(key);
console.log(val);
jQuery(childElements[child]).text(val)
}));
});
}
Run Code Online (Sandbox Code Playgroud)
上面的代码执行替换,但它实际上替换它显示为undefined.
因此,如果原始字符串是所有人的Hello world并且我想要将world替换为with <b>world to</b>,则它在console.log中显示为Hello undefined all
bob*_*nce 13
通常,改变页面内容html()与使用正则表达式替换标记一样简单.如果标记本身存在匹配的文本,那么所有这些尝试都将失败,当浏览器选择以不符合您期望的方式序列化其DOM时可能会失败,并且最好,当它确实有效时,仍会强制您序列化并重新解析所有搜索到的文本,这些文本很慢并且会破坏所有不可序列化的信息,例如表单字段值,JavaScript引用和事件处理程序.对于简单的低级元素,你可以侥幸逃脱,但对于像<body>它一样糟糕的容器.
更好:不是黑客攻击HTML字符串,而是坚持使用实时DOM节点,搜索Text符合您要求的节点并对直文节点数据进行替换.这里有一些简单的JS代码(如果你愿意,我想你可以将它放在一个插件中.)
// Utility function to find matches in an element's descendant Text nodes,
// calling back a function with (node, match) arguments. The `pattern` can
// be a string, for direct string matching, or a RegExp object (which must
// be a `g`lobal regex.
//
function findText(element, pattern, callback) {
for (var childi= element.childNodes.length; childi-->0;) {
var child= element.childNodes[childi];
if (child.nodeType==1) {
var tag= child.tagName.toLowerCase();
if (tag!=='script' && tag!=='style' && tag!=='textarea')
findText(child, pattern, callback);
} else if (child.nodeType==3) {
var matches= [];
if (typeof pattern==='string') {
var ix= 0;
while (true) {
ix= child.data.indexOf(pattern, ix);
if (ix===-1)
break;
matches.push({index: ix, '0': pattern});
}
} else {
var match;
while (match= pattern.exec(child.data))
matches.push(match);
}
for (var i= matches.length; i-->0;)
callback.call(window, child, matches[i]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用纯字符串搜索词的示例:
// Replace “World to” string in element text with <i>-wrapped version
//
var element= $('#construct_version')[0];
findText(element, 'World to', function(node, match) {
var wrap= document.createElement('i');
node.splitText(match.index+match[0].length);
wrap.appendChild(node.splitText(match.index));
node.parentNode.insertBefore(span, node.nextSibling);
});
Run Code Online (Sandbox Code Playgroud)
你可以使用.replace(),例如:
var str = "Hello world to all people";
str = str.replace(/(world to all)/g, "<i>$1</i>");
Run Code Online (Sandbox Code Playgroud)
你可以试试这里应用来说一个元素的html:
$("span").html(function(i, t) {
return t.replace(/(world to all)/g, "<i>$1</i>");
});
Run Code Online (Sandbox Code Playgroud)