使用 jquery 设置 div 标签的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1570905/
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
Use jquery to set value of div tag
提问by air
I have this html div tag defined:
我定义了这个 html div 标签:
<div style="height:100px; width:100px" class="total-title">
first text
</div>
I have jquery code to change its value:
我有 jquery 代码来改变它的值:
$('div.total-title').html('test');
But this does not change the content of the div.
但这不会改变 div 的内容。
回答by farzad
if your value is a pure text (like 'test') you could use the text() method as well. like this:
如果您的值是纯文本(如“test”),您也可以使用 text() 方法。像这样:
$('div.total-title').text('test');
anyway, about the problem you are sharing, I think you might be calling the JavaScript code before the HTML code for the DIV is being sent to the browser. make sure you are calling the jQuery line in a <script> tag after the <div>, or in a statement like this:
无论如何,关于您正在分享的问题,我认为您可能在将 DIV 的 HTML 代码发送到浏览器之前调用了 JavaScript 代码。确保在 <div> 之后的 <script> 标记中调用 jQuery 行,或在如下语句中调用:
$(document).ready(
function() {
$('div.total-title').text('test');
}
);
this way the script executes after the HTML of the div is parsed by the browser.
这样脚本在 div 的 HTML 被浏览器解析后执行。
回答by MaLKaV_eS
To put text, use .text('text')
要放置文本,请使用 .text('text')
If you want to use .html(SomeValue)
, SomeValue should have html tags that can be inside a div it must work too.
如果你想使用.html(SomeValue)
SomeValue 应该有 html 标签,可以在一个 div 里面,它也必须工作。
Just check your script location, as farzad said.
正如farzad所说,只需检查您的脚本位置。
回答by Alex H
try this function $('div.total-title').text('test');
试试这个功能 $('div.total-title').text('test');
回答by djdd87
You have referenced the jQuery JS file haven't you? There's no reason why farzad's answer shouldn't work.
您已经引用了 jQuery JS 文件,不是吗?farzad 的回答没有理由不工作。
回答by Jo Smo
When using the .html()
method, a htmlString
must be the parameter. (source) Put your string inside a HTML tag and it should work or use .text()
as suggested by farzad.
使用该.html()
方法时,ahtmlString
必须是参数。( source) 将您的字符串放在 HTML 标记中,它应该可以.text()
按照 farzad 的建议工作或使用。
Example:
例子:
<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
</div>
<script type="text/javascript">
$("div.demo-container").html( "<p>All new content. <em>You bet!</em></p>" );
</script>
回答by Rishabh
use as below:
使用如下:
<div id="getSessionStorage"></div>
<div id="getSessionStorage"></div>
For this to append anything use below code for reference:
为此,请使用以下代码附加任何内容以供参考:
$(document).ready(function () {
var storageVal = sessionStorage.getItem("UserName");
alert(storageVal);
$("#getSessionStorage").append(storageVal);
});
This will appear as below in html (assuming storageVal="Rishabh")
这将在 html 中显示如下(假设 storageVal="Rishabh")
<div id="getSessionStorage">Rishabh</div>