我有一篇关于“颜色”这个词的例子的文章。我在.colour类中设置了一个按钮,这样如果您想要单击它,可以在整个页面中将拼写从“颜色”更改为“颜色”。为此,我编写了一些jQuery,但是它只改变了单词颜色的一个实例,而不是所有的实例。您必须不停地单击按钮才能更改所有按钮。
$(document).ready(function(){
$(".colour").click(function(){
$("body").children().each(function() {
$(this).html($(this).html().replace("color","colour"));
});
})
})是否有一种方法可以反复循环脚本,直到它更改所有实例?另外,它是否有可能使它不区分大小写?我对javascript和jquery很陌生,所以可能是个菜鸟问题。谢谢
发布于 2014-09-19 16:39:20
让您的替换使用正则表达式和全局替换。
更改:
$(this).html().replace("color","colour")至:
$(this).html().replace(/color/g,"colour");发布于 2014-09-19 16:45:28
例如,我不太喜欢在这种情况下使用.html(),所以
$(document).ready(function(){
$(".colour").click(function(){
$("body *").contents().each(function() {
if(this.nodeType==3){
this.nodeValue = this.nodeValue.replace(/color/g, 'colour')
}
});
})
})h2.colour, h2.color{
font-size:16px;
max-width: 200px;
margin: 1em auto;
text-align: center;
padding:0.4em;
color: #999;
background-color: #ccc;
@include border-top-radius(5px);
@include border-bottom-radius(5px);
@include transition (all 0.3s ease-in-out);
}
h2.colour:hover, h2.color:hover{
color: #000;
background-color: #aaa;
}
p{
max-width: 400px;
margin: 1em auto;
margin-top: 5em;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="text">
Seasonal Colors: Some colors are more appropriate at certain times of year than others. Pastels are usually associated with spring/summer, while autumn colors are rust, <span style="color:brown">brown</span>, <span style="color:green">green</span>, and <span style="color:firebrick">burgundy</span>. Wearing rust in the summer, or light yellow in the fall looks out of place. That color's place in society. Second lower case color.
</p>
<h2 class="colour">Colour</h2>
我在使用.html()时看到的两个问题是
发布于 2014-09-19 16:42:13
找到所有并替换
$(this).html().split('color').join("colour");https://stackoverflow.com/questions/25938585
复制相似问题