如何使用 jQuery 更改文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6411696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change a text with jQuery
提问by shin
I have an h1with id of toptitlethat is dynamically created, and I am not able to change the HTML.
It will have a different title depends on a page. Now when it is Profile, I want to change it to New wordwith jQuery.
我有一个动态创建的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>
Note: If the text is Profile, then change it to New word.
注意:如果文本是Profile,则将其更改为New word。
采纳答案by lonesomeday
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 textin the jQuery API.
这仅在内容为 时替换内容Profil。请参阅textjQuery API。
回答by Andrew Whitaker
回答by Nicola Peluchetti
Something like this should work
这样的事情应该工作
var text = $('#toptitle').text();
if (text == 'Profil'){
$('#toptitle').text('New Word');
}
回答by Niklas
Could do it with :contains()selector as well:
也可以用:contains()选择器来做:
$('#toptitle:contains("Profil")').text("New word");
example: http://jsfiddle.net/niklasvh/xPRzr/
回答by Joshua Pinter
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');
回答by OHLáLá
$('#toptitle').html('New world');
or
或者
$('#toptitle').text('New world');
回答by agmcleod
Pretty straight forward to do:
非常直接的做法:
$(function() {
$('#toptitle').html('New word');
});
The html function accepts html as well, but its straight forward for replacing text.
html 函数也接受 html,但它直接用于替换文本。

