在 jquery 中设置文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4511804/
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
set text in jquery
提问by sehummel
If I want to set the text of a <div id="error"></div>
to "Test message here", do I do:
如果我想将 a 的文本设置<div id="error"></div>
为“在这里测试消息”,我应该这样做:
$('<div id="error">').text('Test message here');
I tried this and it's not working. Thoughts?
我试过这个,但它不起作用。想法?
回答by Gabi Purcaru
You create a new div and set its text, but you don't insert it anywhere. What you need to do is:
您创建一个新的 div 并设置其文本,但没有将其插入任何地方。你需要做的是:
var el = $('<div id="error">').text('Test message here');
$(document).append(el);
or, if the div is already there:
或者,如果 div 已经存在:
$("#error").text('Test message here');
回答by Dejan Marjanovic
$('#error').text('Test message here');
回答by álvaro González
Try:
尝试:
$('<div id="error"></div>').text('Test message here');
You also need to insert the new element somewhere in the page.
您还需要在页面中的某处插入新元素。
回答by Murugan
It's preferable to use
最好使用
$("#error").html('Test message here')
instead of simply
而不是简单地
.text('Text Msg');