如何使用 jQuery 更改文本

我有一个 ID 为 toptitleh1,它是动态创建的,我无法更改 HTML。 它将有一个不同的标题取决于一个页面。现在,当它是 Profile 时,我想用 jQuery 将它更改为 New word

<h1 id="toptitle">Profile</h1> // Changing only when it is Profile
// to
<h1 id="toptitle">New word</h1>

注意: 如果文本为 Profile,则改为 New word

306786 次浏览

This should work fine (using .text():

$("#toptitle").text("New word");
$('#toptitle').html('New world');

or

$('#toptitle').text('New world');

Pretty straight forward to do:

$(function() {
$('#toptitle').html('New word');
});

The html function accepts html as well, but its straight forward for replacing text.

Something like this should do the trick:

$(document).ready(function() {
$('#toptitle').text(function(i, oldText) {
return oldText === 'Profil' ? 'New word' : oldText;
});
});

This only replaces the content when it is Profil. See text in the jQuery API.

Something like this should work

var text = $('#toptitle').text();
if (text == 'Profil'){
$('#toptitle').text('New Word');
}

Could do it with :contains() selector as well:

$('#toptitle:contains("Profil")').text("New word");

example: http://jsfiddle.net/niklasvh/xPRzr/

Cleanest

Try this for a clean approach.

var $toptitle = $('#toptitle');


if ( $toptitle.text() == 'Profile' ) // No {} brackets necessary if it's just one line.
$toptitle.text('New Word');

*In my case i have stored the new Value in the var altText

$('#toptitle').text(altText);

* And it Worked