在jQuery中创建div元素[重复]

本文翻译自:Creating a div element in jQuery [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

How do I create a div element in jQuery ? 如何在jQuery中创建div元素?


#1楼

参考:https://stackoom.com/question/3dme/在jQuery中创建div元素-重复


#2楼

Here's another technique for creating divs with jQuery. 这是使用jQuery创建div的另一种技术。

ELEMENT CLONING 元素克隆

Say you have an existing div in your page that you want to clone using jQuery (eg to duplicate an input a number of times in a form). 假设您在页面中有一个想要使用jQuery克隆的div(例如,在表单中多次复制输入)。 You would do so as follows. 你会这样做。

 $('#clone_button').click(function() { $('#clone_wrapper div:first') .clone() .append('clone') .appendTo($('#clone_wrapper')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="clone_wrapper"> <div> Div </div> </div> <button id="clone_button">Clone me!</button> 


#3楼

I've just made a small jQuery plugin for that. 我刚刚制作了一个小的jQuery插件

It follows your syntax: 它遵循您的语法:

var myDiv = $.create("div");

DOM node ID can be specified as second parameter: DOM节点ID可以指定为第二个参数:

var secondItem = $.create("div","item2");

Is it serious? 这是认真的吗? No. But this syntax is better than $("<div></div>") , and it's a very good value for that money. 不。但是这种语法比$(“<div> </ div>”)好 ,而且这个钱非常好。

(Answer partially copied from: jQuery document.createElement equivalent? ) (答案部分复制自: jQuery document.createElement等价?


#4楼

You can create separate tags using the .jquery() method. 您可以使用.jquery()方法创建单独的标记。 And create child tags by using the .append() method. 并使用.append()方法创建子标记。 As jQuery supports chaining, you can also apply CSS in two ways. 由于jQuery支持链接,您还可以通过两种方式应用CSS。 Either specify it in the class or just call .attr() : 在类中指定它或只调用.attr()

var lTag = jQuery("<li/>")
.appendTo(".div_class").html(data.productDisplayName);

var aHref = jQuery('<a/>',{         
}).appendTo(lTag).attr("href", data.mediumImageURL);

jQuery('<img/>',{                                               
}).appendTo(aHref).attr("src", data.mediumImageURL).attr("alt", data.altText);

Firstly I am appending a list tag to my div tag and inserting JSON data into it. 首先,我将一个list标签附加到我的div标签并将JSON数据插入其中。 Next, I am creating a child tag of list, provided some attribute. 接下来,我创建了一个列表的子标记,提供了一些属性。 I have assigned the value to a variable, so that it would be easy for me to append it. 我已将值赋给变量,因此我很容易追加它。


#5楼

If it is just an empty div, this is sufficient: 如果它只是一个空div,这就足够了:

$("#foo").append("<div>")

or 要么

$("#foo").append("<div/>")

It gives the same result. 它给出了相同的结果。


#6楼

A short way of creating div is 创建div的一个简短方法是

var customDiv = $("<div/>");

Now the custom div can be appended to any other div. 现在自定义div可以附加到任何其他div。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值