插件
下面是我写的一个插件,它允许你创建一个元素,简单地用属性装饰它,并将它附加到 DOM。下面是一个使用 .adorn() 的示例:
$("<div>").adorn("#errors",".red",">body");
上面创建了一个div,在ID 和Class 上拍打,并将其全部附加到body。请注意,您可以按任意顺序添加 appendTo 语法,所以这也可以:
$("<div>").adorn(">body","#errors",".red");
与使用一个连续字符串相反,我发现将每个类、id、值等作为参数传递更容易,因为这清楚地描述了它们。
语法:
-
.blah - 添加类 blah
-
#blah - 将 id 设置为 blah
-
>blah - 将此附加到 blah
-
h:blah - 将 innerHTML 设置为 blah
-
v:blah - 将值设置为 blah
- 目前有9个选项
- ...您可以轻松添加新功能。
请注意,使用时,冒号可以是任何单个字符,不一定是冒号,所以h-blah 也可以。
其他用途:
这个插件的好处是它不仅可以用来装饰新创建的元素,还可以用来装饰现有元素。例如添加 3 个类并为页面上的所有 div 设置 HTML:
$("div").adorn(".one",".two",".three","h:blah");
最后,如果你不小心传入了错误的标签。 An error class is added to the element 以简化调试,但不会中断。
工作原理:
这个插件的核心是利用自动可用的 arguments array 来保存所有传入的选项。使用 switch statement 和 substring method 解析选项。
插件:
(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 );