jQuery查找替换多个单词

3
我正在尝试在同一个
中替换多个单词。
显然这样行不通,以下是我的代码。
$("#Number").each(function() {
    var text = $(this).text();
    $(this).text(text.replace("Monster", "Witch")); 
});
$("#Number").each(function() {
    var text = $(this).text();
    $(this).text(text.replace("Girl", "Boy")); 
});

感谢您的请求。
谢谢。

2个回答

5

Replace无法接受多个参数,但您可以将其链接在一起使用,例如:

$("#Number").each(function() {
    $(this).html($(this).html().replace('find1', 'replace1').replace('find2', 'replace2'));
});

3
你可以简单地使用正则表达式来替换字符串中的所有出现。
$(".Number").each(function() {
    $(this).text($(this).text().replace(/Monster/g, "Witch")); 
});
$(".Number").each(function() {
    $(this).text($(this).text().replace(/Girl/g, "Boy")); 
});

这里有一个工作的JSFiddle链接

注意:需要记住,不能有两个拥有相同ID(以'#'表示)的元素。所以,我将属性和选择器改为了class。
如果你只想更改一个元素上的值,你可以将第二个代码块的逻辑移到第一个代码块的主体中:

$("#Number").each(function() {
    $(this).text($(this).text().replace(/Monster/g, "Witch")); 
    $(this).text($(this).text().replace(/Girl/g, "Boy")); 
});

2
“你不能有两个具有相同ID的元素”,虽然这是违反惯例的,但没有任何理由阻止你这样做。Rails页面经常这样做。如果您需要获取它们中的所有内容,请将选择器更改为:“$('[id=Number]')”。查询中的“#”只会返回第一条记录。 - Camway
好的,我想表达的是你不应该有两个具有相同ID的元素。 - rageandqq

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接