Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.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
Jquery 替换html以在具有相同类的div中添加空格_Jquery - Fatal编程技术网

Jquery 替换html以在具有相同类的div中添加空格

Jquery 替换html以在具有相同类的div中添加空格,jquery,Jquery,我知道以前有人问过这个问题,但我找不到我具体问题的正确答案。我想在小写和大写之间添加空格,只在具有特定类的div中添加 假设我有这个html: <div class='type'>CreditCard</div> <div class='type'>DebitCard</div> 结果: <div class='type'>Credit Card</div> <div class='type'>Credit C

我知道以前有人问过这个问题,但我找不到我具体问题的正确答案。我想在小写和大写之间添加空格,只在具有特定类的div中添加

假设我有这个html:

<div class='type'>CreditCard</div>
<div class='type'>DebitCard</div>
结果:

<div class='type'>Credit Card</div>
<div class='type'>Credit Card</div>

信用卡

DebitCard
您应该添加for循环

$('.type').html()
只需获取第一个元素的html并应用于所有
$('.type')

$('.type')。每个(函数(elem){
$(this.html($(this.html().replace(/([a-z])([a-z])/g,“$1$2”);
})

信用卡

DebitCard
代码的问题是html()只将其返回到集合中的第一个元素。然后将其应用于集合中的所有元素。您需要在集合上循环。因此,您可以使用each()或html()/text()中的函数。方法参数是index和text/html。返回要应用于该索引的字符串

$(“.type”).text(
函数(索引,txt){
返回txt.replace(/([a-z])([a-z])/g,“$1$2”);
}
);

信用卡

DebitCard
html()返回集合中的第一项,但它不会神奇地将其应用于所有项。感谢您的评论,两个答案都是正确的。我知道有什么不对劲,但我不知道为什么。
$('.type').html($('.type').html().replace(/([a-z])([A-Z])/g, "$1 $2"));
<div class='type'>Credit Card</div>
<div class='type'>Credit Card</div>