使用 JQuery 动态添加 Div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5852686/
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
Add Div Dynamically using JQuery
提问by JD Audi
I'm not sure if this would be the best option.. But I want the option that when the user clicks a button, it will add another div or li.
我不确定这是否是最好的选择。但我想要一个选项,当用户单击一个按钮时,它会添加另一个 div 或 li。
I am going to allow users to upload documents, but multiple ones. I'd like to for the user to be able to click a button, and a new <div>
or <li>
is generated with predefined code. Is this possible?
我将允许用户上传文件,但要上传多个文件。我希望用户能够点击一个按钮,并使用预定义的代码生成一个新的<div>
或<li>
生成的。这可能吗?
Here's a fiddle..
这是一个小提琴..
采纳答案by BrunoLM
Your example updated on jsFiddle
$("input[type=submit]").click(function(){
$("<li />").html("item").appendTo("ul");
})
You can create elements using $("<tag />")
and set attributes, add classes and so on. Then append where you want.
您可以使用$("<tag />")
和设置属性来创建元素、添加类等。然后附加到你想要的地方。
回答by theabraham
Try this:
尝试这个:
$('.button').click(function() {
$('#myContainer').append('<div>the new guy</div>');
});
回答by Matt Ryan
You can add a new element to an existing parent like so:
您可以将新元素添加到现有父元素,如下所示:
select the element to added the new <div>/<li>
to and use .append()
选择要添加新元素<div>/<li>
并使用的元素.append()
$("#id").append("<div>foo</div>");
$("#id").append("<div>foo</div>");
Alternatively, you can use the .html()
或者,您可以使用 .html()
回答by Jeremy Battle
If this is to allow for multiple file uploads, have you considered using something like http://www.uploadify.com/the jQuery plugin? It allows multiple file uploads from one dialog window and you wouldn't need to worry about this.
如果这是为了允许多个文件上传,您是否考虑过使用类似http://www.uploadify.com/的 jQuery 插件?它允许从一个对话窗口上传多个文件,您无需担心这一点。
回答by dhana govindarajan
$("input[type=submit]").click(function(){ $("").html("item").appendTo("ul"); })
$("input[type=submit]").click(function(){ $("").html("item").appendTo("ul"); })
You can create elements using $("") and set attributes, add classes and so on. Then append where you want.
您可以使用 $("") 创建元素并设置属性、添加类等。然后附加到你想要的地方。