jQuery可以通过选择器创建一个元素吗?
通常我会在jQuery中创建一个元素,如$('
')
我可以使用$.create("div#errors.red")
类的东西创建一个给定选择器的元素吗? 哪里会返回一个jQuery对象,表示一个id为errors
的id和red
的类?
你的意思是像DOM创建一样的Zen Coding。 您可以在zen编码Google项目页面上找到zen编码的语法。
用法是:
1. 下载并添加zen-0.1.a.js文件并将其添加到您的主页
2.将此function添加到您的项目中
var zen = function(input) { return jQuery(zen_coding.expandAbbreviation(input, 'html', 'xhtml')); };
3.创建jQuery dom:
var dom = zen('div#id.class'); $('body').append(dom);
一个插件
下面是我编写的一个插件,它允许您创建一个元素,只需用属性装饰它,然后将它附加到DOM。 这是一个使用.adorn()
的例子,你想做什么:
$("").adorn("#errors",".red",">body");
上面创建了一个div
,一个ID
和一个Class
slaps,并将它全部附加到body
。 请注意,您可以按任何顺序添加appendTo
语法,因此这也适用:
$("").adorn(">body","#errors",".red");
使用adorn创建的简单示例页面。
与使用一个连续字符串相反,我发现将每个类,id,值等作为参数传递更容易,因为这清楚地描述了它们。
句法:
-
.blah
– 加上课堂blah
-
#blah
– 将id设置为blah
-
>blah
– 加上这个blah
-
h:blah
– 将innerHTML设置为blah
-
v:blah
– 将价值设定为blah
- 目前有9种选择
- …您可以轻松添加新function。
请注意,使用时,冒号可以是任何单个字符,它不必是冒号,因此h-blah
也可以。
其他用途:
这个插件的好处在于它不仅可以用来装饰新创建的元素,还可以用来装饰现有元素。 例如,添加3个类并为页面上的所有div设置HTML:
$("div").adorn(".one",".two",".three","h:blah");
jsFiddle示例
最后,如果你不小心传递了错误的标签。 向元素添加了一个错误类以简化调试,但事情不会中断。
这个怎么运作:
这个插件的核心是利用自动可用的参数数组来保存所有传入的选项。 使用switch语句和substring方法解析选项。
插件:
(function( $ ){ jQuery.fn.adorn = function () { // Get the arguments array for use in the closure var $arguments = arguments; // Maintain chainability return this.each(function () { var $this = $(this); $.each($arguments, function(index, value) { // These are just the options that quickly came // to mind, you can easily add more. // Which option is used depends on the first // character of the argument passed in. The 2nd // char is sometimes used and sometimes ignored. switch (value.substring(0,1)) { case "#": $this.attr("id",value.substring(1)); break; case ".": $this.addClass(value.substring(1)); break; case ">": $this.appendTo(value.substring(1)); break; case "a": $this.attr("alt", value.substring(2)); break; case "h": $this.html(value.substring(2)); break; case "i": $this.attr("title", value.substring(2)); break; case "s": $this.attr("src", value.substring(2)); break; case "t": $this.attr("type", value.substring(2)); break; case "v": $this.attr("value", value.substring(2)); break; default: // if the wrong key was entered, create // an error class. $this.addClass("improper-adorn-label"); } }); }); }; })( jQuery );
我不认为你能做到这一点,我知道的更接近的事情就是你能做到
var newdiv = $.DIV({ className: "red", id: "errors"});
div已创建,您可以将事件和内容直接附加到变量
使用此插件http://mg.to/2006/02/27/easy-dom-creation-for-jquery-and-prototype
你可以试试这个方法:
$("").appendTo("body");