【问题标题】:Jquery find replace multiple wordsjQuery查找替换多个单词
【发布时间】:2015-04-21 01:58:17
【问题描述】:

我正在尝试替换同一 div 中的多个单词。
显然这行不通,这是我的代码。

$("#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")); 
});

谢谢。

【问题讨论】:

标签: jquery replace find words


【解决方案1】:

替换不能接受多个参数但可以链式,例如:

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

【讨论】:

    【解决方案2】:

    您可以简单地使用正则表达式替换字符串中的所有匹配项。

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

    查看工作中的JSFiddle here

    注意:请记住,不能有两个具有相同 ID(用“#”表示)的元素。因此,我将属性和选择器更改为类。
    如果您只想更改一个元素的值,可以将逻辑从第二个块移动到第一个块的主体:

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

    【讨论】:

    • "你不能有两个具有相同 ID 的元素" 没有任何理由你不能,尽管这违反了惯例,rails 页面一直这样做。如果您需要获取所有这些,只需将您的选择器更改为:$('[id=Number]')。查询中的“#”只是告诉 javascript 只返回第一条记录。
    • 很公平,我想我的意思是你不应该有两个具有相同 ID 的元素。
    猜你喜欢
    • 2012-10-27
    • 2012-01-04
    • 1970-01-01
    • 2015-06-16
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多