Jquery用一个类替换所有DIV内部的点和空格

Jquery replace dots with spaces inside of all DIVs with one class

本文关键字:内部 DIV 空格 替换 一个 Jquery      更新时间:2023-09-26

我正在使用最新的Jquery和以下脚本:

<script type="text/javascript">
$(document).ready(function(){
var el = $('.title');
el.html(el.html().replace(/'./gi, " "));
});
</script>

这是div:

<div class="title">The.quick.brown.fox</div>

它所做的是用类"title"的DIV中的空格替换所有的点,实际上它很适合这份工作。

但我有很多DIV,它们有相同的"title"类,但有不同的字符串,我需要它们都用空格替换点。但这里的问题出现了,因为我在所有这些DIV"the quick brown fox"上得到的都是相同的结果字符串,而所有的结果字符串都应该不同,因为所有的源字符串都不同。。。

我该怎么做才能将所有DIV中的点替换为类"title"和每个DIV中所有不同的字符串?

感谢

您可以使用each()来迭代匹配的元素,或者将函数传递给html()并在那里计算新文本:

$(document).ready(function() {
    $(".title").html(function(index, currentHtml) {
        return currentHtml.replace(/'./gi, " ");
    });
});

只需使用jQuery each方法迭代.title:类的所有元素

$(document).ready(function(){
  $('.title').each(function(){
    $(this).html($(this).html().replace(/'./gi, " "));
  });
});

只要div中只有文本,建议的函数就可以正常工作。然而,为了允许任意html(如The.quick.brown <img src='fox.jpg'>),代码应该更准确。

$('.title').each(function() {
    if (this.nodeType == 3)
        this.nodeValue = this.nodeValue.replace(/'./g, " ");
    else
        $(this).contents().each(arguments.callee);
});

基本上,您递归地迭代一个节点的所有子节点,只替换类型为3(=text)的节点。

Fiddle:http://jsfiddle.net/jZgUY/