如何使用 jQuery 更改 Span 的内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2622282/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:53:41  来源:igfitidea点击:

How to change the content of the Span using jQuery?

jqueryhtmlcss

提问by Swati Sharma

<span class="stbuttontext" st_page="home">ShareThis</span>

I want to change "Share This" to "Share",

我想把“分享这个”改为“分享”,

please let me know the solution.

请让我知道解决方案。

thanksl,

谢谢,

回答by Sarfraz

You can do with either:

您可以使用以下任一方法:

$('.stbuttontext').text('Share');

for textualcontent or

对于文本内容或

$('.stbuttontext').html('Share');

for htmlcontents.

对于html内容。

In your case however, the first statement should be fine :)

但是,在您的情况下,第一条语句应该没问题:)

回答by Christopher Altman

This is my way of thinking about when to use .html() vs. .text().

这是我思考何时使用 .html() 与 .text() 的方式。

Use .html() when you want to add styling with html tags to the text you are replacing, like:

当您想将带有 html 标签的样式添加到要替换的文本时,请使用 .html() ,例如:

$('.stbuttontext').html('<strong>Share</strong>');

This is ofter useful when you are displaying an error message because you may want to add a class to change the color of the text.

这在您显示错误消息时非常有用,因为您可能想要添加一个类来更改文本的颜色。

$('#error').html('<span class="errortext red"><strong>Error:</strong> <em>Fix your email address</em></span>');`

Use .text() when you simply want to change the text.

当您只想更改 text 时,请使用 .text()

So if you did the above example with .text:

所以如果你用 .text 做上面的例子:

$('#error').text('<span class="errortext red"><strong>Error:</strong> <em>Fix your email address</em></span>');

$('#error').text('<span class="errortext red"><strong>Error:</strong> <em>Fix your email address</em></span>');

The text the user will see on the web page is (without the spaces in the tags, I could not figure out how to get it to work with this markdown editor).

用户将在网页上看到的文本是(没有标签中的空格,我不知道如何让它与这个 Markdown 编辑器一起工作)。

< span class="errortext red">< strong>Error: < em>Fix your email address< /em>< /span>

<span class="errortext red"><strong>错误:<em>修复您的电子邮件地址</em></span>

and that text is not red, or have bold or italic text.

并且该文本不是红色的,或者具有粗体或斜体文本。

回答by Fitzchak Yitzchaki

$('.stbuttontext').html('Share');
$('.stbuttontext').html('Share');

回答by Egor Pavlikhin

$('.stbuttontext').html('Share');

$('.stbuttontext').html('Share');

Will change the text of all spans with the class stbuttontext.

将使用类 stbuttontext 更改所有跨度的文本。