簡體   English   中英

使用javascript替換文本

[英]Replace the text using javascript

我使用下面的代碼來替換h1標簽中的文本,但它沒有受到影響。 我想將“sample”替換為“new sample”。 我做錯了?

<div class="content">
<h2>sample</h2>
</div>

var t = jQuery('.content');
        t.children("h2").each(function() {
            var contents = jQuery(this).contents();
            jQuery(this).replaceWith(new sample);
        });

使用.html()來設置html.try:

 $('.content h2').html('new sample');

工作演示

設置.text()

t.children("h2").text('new sample'));


如果要設置.html()內容

 t.children("h2").html('new sample')); 

子選擇器(“父>子”)

 $('.content > h2').html('new sample'); 

使用jQuery的.text()

$(".content h2").text("new sample");

小提琴

如果您想要替換部分內容,請嘗試以下操作:

jQuery('.content h2').each(function(i, v) {
    $v = $(v);
    $v.html($v.html().replace('sample', 'new sample'));
});

的jsfiddle

你可以不用jQuery做到這一點:

var elem = document.getElementsByTagName('h2')[0];
elem.innerHTML = "New Value";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM