Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery重复出现替换innerHTML_Javascript_Jquery - Fatal编程技术网

Javascript jQuery重复出现替换innerHTML

Javascript jQuery重复出现替换innerHTML,javascript,jquery,Javascript,Jquery,我有一个基于id属性的工作脚本。因为我有很多问题,所以决定在jQuery中使用class属性。但是我不能成功地使用以下脚本(我不擅长编写脚本:() 如果你能给我一个更好的建议,那就太好了。我有300多个单词要用符号来代替(大约200页) 非常感谢 HTML代码 默认内容 默认内容2 java脚本 $('#replace').click(function() { var str=document.getElementByClassName("my_div").innerHTML;

我有一个基于id属性的工作脚本。因为我有很多问题,所以决定在jQuery中使用class属性。但是我不能成功地使用以下脚本(我不擅长编写脚本:()

如果你能给我一个更好的建议,那就太好了。我有300多个单词要用符号来代替(大约200页)

非常感谢

HTML代码


默认内容
默认内容2
java脚本

$('#replace').click(function() {
     var str=document.getElementByClassName("my_div").innerHTML;
     var n=str.replace("default","somesymbol");
     var n=str.replace("content","somesymbol");
     var n=str.replace("im","somesymbol");
     document.getElementByClassName("my_div").innerHTML=n;
    }

改用类似的方式:

$('#replace').click(function() {
    $('.my_div').each(function() {
        var $this = $(this);
        var html = $this.html();

        $this.html(html.replace(/default|content|im/gi, 'somesymbol'));
    });
}​);​
getElementByClassName
应该是
getElementsByClassName
,它返回一个必须迭代的
NodeList

此外,如果您不需要在替换中保留格式(如
foo-bar
),请使用jQuery
html()使用
.text()
,而不是
.html()
方法如果使用函数作为参数,它将使用类名在整个元素集合上循环,自动授予您对现有html的访问权限,并在返回html字符串时替换它

$('#replace').click(function() {
    $('.my_div').html(function( idx, oldHtml){
    /* if you need access to other properties or attributes of element -"this" or "$(this)" within this function*/
           return oldHtml.replace(/default|content|im/gi, 'somesymbol');
    });
});
参考:


向下查看API页面,查看jQuery 1.4版中添加的部分,非常感谢,它工作得很好。但是如何应用到不同的替换示例集以下内容不起作用:返回oldHtml.replace(/default/gi,'somesymbol');返回oldHtml.replace(/content/gi,'new');