jQuery替换许多类中的字符串 [英] jQuery replace strings in many classes
问题描述
我正在尝试使用jQuery替换某个类中发生的特定字符串的所有出现。这个页面上有多个类。
I'm trying to use jQuery to replace all occurrences of a particular string that occurs in a certain class. There are multiple classes of this type on the page.
到目前为止,我有以下代码:
So far I have the following code:
var el = $('div.myclass');
if(el != null && el.html() != null )
{
el.html(el.html().replace(/this/ig, "that"));
}
如果有多个div,类 MyClass的
。如果有多个div,那么第二个div将被替换为第一个div的内容!就像jQuery在第一个div上执行替换,然后用结果替换所有类别的 myclass
。
This doesn't work if there is more than one div with class myclass
. If there is more than one div then the second div is replaced with the contents of the first! It is as if jQuery performs the replacement on the first div and then replaces all classes of myclass
with the result.
mychass divs的所有实例进行一些循环 - 但是我的JS有点弱。
Anyone know how I should be doing this? I'm thinking some kind of loop over all instances of mychass
divs - but my JS is a bit weak.
推荐答案
与以前的答案略有不同:
slightly different of previous answer:
$('div.myclass').each(function(i, el) {
if($(el).html() != "" ) {
$(el).html($(el).html().replace(/this/ig, "that"));
}
});
应该工作
这篇关于jQuery替换许多类中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!