如何使用 jQuery 在 div 中编写元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6065291/
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 an element inside a div using jQuery?
提问by DiegoP.
How do I write a <div>
inside another with jQuery?
我如何<div>
用 jQuery 在另一个里面写一个?
I have a <div>
that I can not modify in HTML because I am working in a CMS. So I want to write an element (<div>
) inside this <div>
with a click function.
我有一个<div>
无法在 HTML 中修改的内容,因为我在 CMS 中工作。所以我想用点击函数<div>
在里面写一个元素()<div>
。
I already have created the click function, but how do I write with jQuery a <div>
INSIDE another specific <div>
?
我已经创建了 click 函数,但是如何使用 jQuery 编写<div>
另一个特定的INSIDE <div>
?
回答by Andomar
You could select the existing div, and append a new div to it:
您可以选择现有的 div,并为其添加一个新的 div:
$('#OuterDiv').append('<div id="innerDiv"></div>');
回答by Code Maverick
Like this:
像这样:
$("#div1").click(function() {
$(this).append("<div>new div</div>");
});
or this:
或这个:
$("#div1").click(function() {
var $div = $("<div/>")
.attr("id", "div2")
.html("new div");
$(this).append($div);
});
回答by dclowd9901
$('.clickaclick').click( function(){
$('.parent_div').html('<div />');
});
That should do it, assuming you don't care what's in that .parent_div
. There are so many approaches to doing this kind of thing, it'd do you best to read up a bit on jQuery's DOM insertion methods.
应该这样做,假设你不关心里面有什么.parent_div
。有很多方法可以做这种事情,你最好阅读一下 jQuery 的 DOM 插入方法。
http://api.jquery.com/appendTo/
http://api.jquery.com/appendTo/
http://api.jquery.com/prepend/
http://api.jquery.com/prepend/
http://api.jquery.com/prependTo/
回答by rroche
create a new element
创建一个新元素
$('<div>')
then append that to where you need to
然后将其附加到您需要的位置
$('<div>').text('im a new div').appendTo($('#divId'));
hope this helps
希望这可以帮助
回答by Claudio
You can use the jQuery wrap() method, that will wrap you inner div inside another http://api.jquery.com/wrap/
您可以使用 jQuery wrap() 方法,该方法会将您的内部 div 包裹在另一个http://api.jquery.com/wrap/ 中