jquery1.4发布很久了,也出了几个新的方法,让我们前端设计人员使用起来越来越得心应手啊。
今天讲一个jquery1.4中创建DOM的快捷方法。
在jQ1.4以前我们创建DOM并且添加到DOM树大致是这样的:
1 2 | var oNewp = $("<p>我测试成功了</p>"); oNewp.addClass("red").appendTo("#target"); |
或者,稍微复杂一点:
1 2 3 4 5 6 | $("<div></div>") .attr("id","css") .height(90) .css("border","1px solid #000") .html("fuck world!") .appendTo(document.body); |
jQuery1.4带来了一个全新的便捷地清晰的DOM对象创建方法,在 jQuery 1.4中,我们可以传递一个对象作为第二个参数。 这个参数接受一个属性的集合,这些可以传递给.attr() 方法。此外,一些event type(事件类型)能通过, 而且后面的jQuery方法能够调用: val, css, html, text, data, width, height, or offset。
例如,我们创建一个文本框:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $("<input />",{ "class":"bg-yellow", "id":"jqueryDom", css:{ "border":"1px solid #000", "font-size":"25px" }, value:"fuck world!", focusin:function(){ $(this).css("border","5px solid #FF3300"); }, focusout:function(){ $(this).css("border","1px solid #000"); } }).appendTo(document.body); |
例如,我们创建一个容器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | $("<div></div>",{ "class":"bg-yellow", "id":"jqueryDom", css:{ "border":"1px solid #CDCDCD", "font-size":"25px" }, html:$("<a>",{ href: '#', html:"hello world!", click: function(event) { $("#jqueryDom").css("background-color","#FF3300"); alert("fuck world!!!!!!!!!!"); event.preventDefault(); } }) }).appendTo(document.body); |