javascript 如何使用javascript写入div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11334289/
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 write into div using javascript
提问by user123_456
I want to make a for example content variable in javascript which will have a html tags inside with certain values. How can I put that in the div when button is pressed.
我想在 javascript 中创建一个例如内容变量,它里面会有一个带有某些值的 html 标签。按下按钮时如何将其放入 div 中。
For example :
例如 :
This is a content which I want to use:
这是我想使用的内容:
var contentString = '<div id="info">'+
'<h2><b> Info:</b></h2>'+
'<div id="bodyContent">'+
'<div style=width:220px;display:inline-block;>'+
'<p> Name: '+ this.name + '</p>' +
'<p> Last name: '+ this.last+ '</p>' +
'<p>
'</div>'+
'</div>'+
'</div>'+
'</form>';
And I want to put it into : <div id=something"></div>
In javascript I can have something like:
我想把它放入:<div id=something"></div>
在javascript中,我可以有类似的东西:
$("#button").on('click', function() {
// What to put in here?
});
回答by Blaster
How can I put that in the div when button is pressed.
按下按钮时如何将其放入 div 中。
Like this:
像这样:
$("#button").on('click', function() {
$('#something').html(contentString);
});
More info about html()
;
有关的更多信息html()
;
回答by David says reinstate Monica
If I'm not misunderstanding, then this will work:
如果我没有误解,那么这将起作用:
$("#button").on('click', function() {
$('#something').html(contentString);
});
This does, of course, assume that you have an element with an id
of button
(though I assume you do, otherwise you wouldn't have put that jQuery).
当然,这确实假设您有一个带有id
of的元素button
(尽管我假设您有,否则您就不会放置那个 jQuery)。
References:
参考:
回答by Alfabravo
It goes like this:
它是这样的:
$("#button").on('click', function() {
$("#something").html(contentString);
});
回答by J?rgen
You should fix up your markup. You have unbalanced elements, and you can't have new lines in the string without escaping it. Try this instead:
你应该修正你的标记。你有不平衡的元素,你不能在不转义的情况下在字符串中添加新行。试试这个:
var contentString = '<div id="info">'+
'<h2><b style="text-indent: 40px">Info:</b></h2>'+
'<div id="bodyContent">'+
'<div style="width:220px;display:inline-block;">'+
'<p style="text-indent: 1em">Name: '+ this.name + '</p>' +
'<p style="text-indent: 1em">Last name: '+ this.last+ '</p>' +
'</div>';
Note that I skipped the
and replaced them with style attributes. You really should put these styles in a stylesheet, though.
请注意,我跳过了
并用样式属性替换了它们。不过,您确实应该将这些样式放在样式表中。
$("#button").on('click', function() {
$('#something').html(contentString);
});
Keep in mind that the variables in contentString will not be evaluated when the click event on the button fires, meaning that this.name and this.last will not change. Do you need to update these values on click as well?
请记住,当按钮上的单击事件触发时,不会评估 contentString 中的变量,这意味着 this.name 和 this.last 不会更改。您是否也需要在点击时更新这些值?