我有一个动态创建的h1id toptitle,我无法更改HTML.它将具有不同的标题取决于页面.现在,当它是Profile时,我想New word用jQuery 将其更改为.
<h1 id="toptitle">Profile</h1> // Changing only when it is Profile
// to
<h1 id="toptitle">New word</h1>
Run Code Online (Sandbox Code Playgroud)
注意:如果文本是Profile,则将其更改为New word.
And*_*ker 86
这应该工作正常(使用.text():
$("#toptitle").text("New word");
Run Code Online (Sandbox Code Playgroud)
lon*_*day 58
像这样的东西应该做的伎俩:
$(document).ready(function() {
$('#toptitle').text(function(i, oldText) {
return oldText === 'Profil' ? 'New word' : oldText;
});
});
Run Code Online (Sandbox Code Playgroud)
这只会替换内容Profil.请参阅textjQuery API.
Nic*_*tti 16
这样的事情应该有效
var text = $('#toptitle').text();
if (text == 'Profil'){
$('#toptitle').text('New Word');
}
Run Code Online (Sandbox Code Playgroud)
Nik*_*las 10
也可以用:contains()选择器做到:
$('#toptitle:contains("Profil")').text("New word");
Run Code Online (Sandbox Code Playgroud)
示例:http://jsfiddle.net/niklasvh/xPRzr/
试试这个干净的方法.
var $toptitle = $('#toptitle');
if ( $toptitle.text() == 'Profile' ) // No {} brackets necessary if it's just one line.
$toptitle.text('New Word');
Run Code Online (Sandbox Code Playgroud)
$('#toptitle').html('New world');
Run Code Online (Sandbox Code Playgroud)
要么
$('#toptitle').text('New world');
Run Code Online (Sandbox Code Playgroud)
非常简单:
$(function() {
$('#toptitle').html('New word');
});
Run Code Online (Sandbox Code Playgroud)
html 函数也接受 html,但它可以直接替换文本。
小智 5
*就我而言,我已将新值存储在 var altText 中
$('#toptitle').text(altText);Run Code Online (Sandbox Code Playgroud)
* 它奏效了