如何使用jQuery更改文本


77

我有一个h1IDtoptitle是动态创建的,并且我无法更改HTML。根据页面的不同,标题也会有所不同。现在,当它是Profile时,我想将其更改为New wordjQuery。

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

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

Answers:


67

这样的事情应该可以解决问题:

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

仅当它是时替换内容Profil。参见textjQuery API。





8

最干净

尝试使用这种干净的方法。

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

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

7
$('#toptitle').html('New world');

要么

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

4

很简单地做:

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

html函数也接受html,但是它可以直接替换文本。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.