我正在尝试使用jQuery替换特定类中出现的特定字符串的所有匹配项。页面上有多个此类型的类。
到目前为止,我有以下代码:
var el = $('div.myclass');
if(el != null && el.html() != null )
{
el.html(el.html().replace(/this/ig, "that"));
}
如果有多个div myclass
的div,则不起作用。如果有多个div,那么第二个div将替换为第一个div的内容!就好像jQuery在第一个div上执行替换,然后用结果替换所有myclass
类。
任何人都知道我应该这样做吗?我正在考虑在mychass
div的所有实例上进行某种循环 - 但我的JS有点弱。
答案 0 :(得分:2)
我认为你要找的是这样的:
$('div.myclass').each(function(){
var content = $(this).html();
content = content.replace(/this/ig,'that');
$(this).html(content);
});
(未经测试)
答案 1 :(得分:2)
与之前的回答略有不同:
$('div.myclass').each(function(i, el) {
if($(el).html() != "" ) {
$(el).html($(el).html().replace(/this/ig, "that"));
}
});
应该有效
答案 2 :(得分:0)
如果您的.myclass
元素的内容纯粹是文字内容,那么您可以侥幸成功。但如果它们包含其他元素,则正则表达式处理可能会错误地更改属性值。不要使用正则表达式处理HTML。
同样通过写入innerHTML
/ html()
,您将丢失任何子元素中的任何非可序列化数据,例如表单字段值,事件处理程序和其他JS引用。
function isTextNode(){
return this.nodeType===3; // Node.TEXT_NODE
}
$('div.myclass, div.myclass *').each(function () {
$(this).contents().filter(isTextNode).each(function() {
this.data= this.data.replace(/this/g, 'that');
});
});