我当前使用以下脚本来查找和替换我网站上的文本.
$("#content #tablelabel p").text(function (_, ctx) { return ctx.replace("Check In", "??"); });
Run Code Online (Sandbox Code Playgroud)
但是有数百个单词需要查找和替换.其中一些共享相同的CSS路径.你能告诉我如何优化该脚本并创建一个函数来传递CSS路径和单词来查找和替换,这样我就可以消除重复相同的脚本了吗?
也可以通过替换文本传递多个单词来查找.没有写作的例子
$("#content #tablelabel p").text(function (_, ctx) { return ctx.replace("Room Type", "??"); });
$("#content #tablelabel p").text(function (_, ctx) { return ctx.replace("Guests", "??"); });
Run Code Online (Sandbox Code Playgroud)
我能这样做吗?
$("#content #tablelabel p").text(function (_, ctx) { return ctx.replace({'Room Type': '????','Guests': '????'}); });
Run Code Online (Sandbox Code Playgroud)
谢谢
您可以迭代一个对象,替换它中的所有值
var tags = {
'Room Type': '??',
'Guests': '??'
};
$("#content #tablelabel p").text(function(_, ctx) {
$.each(tags, function(tag, text) {
ctx = ctx.replace(tag, text);
})
return ctx;
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">
<div id="tablelabel">
<p>Room Type</p>
<p>Guests</p>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
不久前我也有同样的愿望.
考虑一下这种用法(我觉得它更强大,更灵活):
//USAGE:
var pattern = [
{
selectors : ["p",".metoo","em"],
find : ["set", "me", "free"],
replace : ["#set#", "@me@", ">free<"]
},
{
selectors : ["h5"],
find : ["I", "quick", "easy"],
replace : ["^ $1 ^"] //$1 is a token to use matched value
}
];
replaceText(pattern);
Run Code Online (Sandbox Code Playgroud)
如您所见,该函数接受一个Array定义元素组的对象,要查找的文本和替换.你可以设置任意多个.
一些说明:
$1 - 将被匹配的值替换.replace数组必须至少有一个值 - 每个匹配的文本将被相应的replace文本替换,否则由前一个文本替换.这是实现它的功能:
var replaceText = function(pat) {
var ret = [];
for (var i = 0; i < pattern.length; i++) {
$(pattern[i].selectors.join(",")).text(function(ind,txt){
for (var j=0; j < pattern[i].find.length; j++) {
if (typeof pattern[i].replace[j] !== 'undefined') {
rep = pattern[i].replace[j].replace("$1", pattern[i].find[j]);
} else if (pattern[i].replace.length) {
rep = pattern[i].replace[pattern[i].replace.length-1].replace("$1", pattern[i].find[j]);
} else { continue; }
txt = txt.replace(pattern[i].find[j], rep);
}
return txt;
});
}
};
Run Code Online (Sandbox Code Playgroud)
小智 5
$("#content #tablelabel p").text( function (_, ctx) {
return ctx.replace('Room Type','????').replace('Guests','????');
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
209 次 |
| 最近记录: |