Jquery替换html中的文本

时间:2011-06-02 08:39:33

标签: javascript jquery html

是否有更优雅的方式替换html元素中的文本而不是:

$el = $("#myDiv");
$el.html( $el.html().replace("something", "something new") );

4 个答案:

答案 0 :(得分:6)

$('#myDiv').html(function(index, oldhtml) {
    return oldhtml.replace('something', 'something new');
});

答案 1 :(得分:1)

如果我理解:

oldText = $('#myDiv').html();
$('#myDiv').html( oldText.replace('something','something new') );

http://jsfiddle.net/wmgBN/

答案 2 :(得分:0)

没有什么比你写的例子更优雅了! 请查看此示例http://blog.chapagain.com.np/jquery-how-to-replace-string-div-content-and-image-src/

答案 3 :(得分:0)

你可以尝试

e1.html(function(i,oldHtml){
     return oldhtml.replace("something", "something new");
}

它的不同但不确定优雅。