Javascript jQuery在许多类中替换字符串
我试图使用jQuery替换某个类中出现的特定字符串的所有实例。页面上有多个此类的类 到目前为止,我有以下代码:Javascript jQuery在许多类中替换字符串,javascript,jquery,dom,Javascript,Jquery,Dom,我试图使用jQuery替换某个类中出现的特定字符串的所有实例。页面上有多个此类的类 到目前为止,我有以下代码: var el = $('div.myclass'); if(el != null && el.html() != null ) { el.html(el.html().replace(/this/ig, "that")); } 如果有多个div具有classmyclass,则这不起作用。如果有多个div,则第二个div将替换为第一个div的内容!就像jQue
var el = $('div.myclass');
if(el != null && el.html() != null )
{
el.html(el.html().replace(/this/ig, "that"));
}
如果有多个div具有classmyclass
,则这不起作用。如果有多个div,则第二个div将替换为第一个div的内容!就像jQuery对第一个div执行替换,然后用结果替换myclass
的所有类一样
有人知道我该怎么做吗?我正在考虑对
mychas
divs的所有实例进行某种循环,但是我的JS有点弱。我认为您需要的是这样的:
$('div.myclass').each(function(){
var content = $(this).html();
content = content.replace(/this/ig,'that');
$(this).html(content);
});
(未经测试)我想你要找的是这样的:
$('div.myclass').each(function(){
var content = $(this).html();
content = content.replace(/this/ig,'that');
$(this).html(content);
});
(未测试)与之前的答案略有不同:
$('div.myclass').each(function(i, el) {
if($(el).html() != "" ) {
$(el).html($(el).html().replace(/this/ig, "that"));
}
});
应该与前面的答案略有不同:
$('div.myclass').each(function(i, el) {
if($(el).html() != "" ) {
$(el).html($(el).html().replace(/this/ig, "that"));
}
});
如果
.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');
});
});
如果
.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');
});
});
谢谢公认的解决方案似乎解决了我的问题。如果我在路上遇到困难,我会重新考虑你的答案。谢谢。公认的解决方案似乎解决了我的问题。如果我在路上遇到困难,我会重新考虑你的答案。