So ändern Sie einen Text mit jQuery


77

Ich habe eine h1mit ID toptitle, die dynamisch erstellt wird, und ich kann den HTML-Code nicht ändern. Es wird einen anderen Titel haben, abhängig von einer Seite. Wenn es sich nun um ein Profil handelt, möchte ich es New wordmit jQuery ändern .

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

Hinweis: Wenn der Text lautet Profile, ändern Sie ihn in New word.

Antworten:


67

So etwas sollte den Trick machen:

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

Dies ersetzt den Inhalt nur, wenn er ist Profil. Siehe textin der jQuery-API.



16

So etwas sollte funktionieren

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


8

Am saubersten

Versuchen Sie dies für einen sauberen Ansatz.

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');

oder

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

4

Ziemlich einfach zu tun:

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

Die HTML-Funktion akzeptiert auch HTML, ist jedoch zum Ersetzen von Text unkompliziert.

Durch die Nutzung unserer Website bestätigen Sie, dass Sie unsere Cookie-Richtlinie und Datenschutzrichtlinie gelesen und verstanden haben.
Licensed under cc by-sa 3.0 with attribution required.