IMO你根本不需要虛擬元素。在下面的例子中,我演示了一種在純javascript中創建元素的簡單方法。
源代碼
createElement: function (options) {
/// <summary>Creates a document object model (DOM) element.</summary>
/// <param name="options" type="Object">An object that contains tag name, attributes, events, properties and children.</param>
var clone = this.extend({}, options);
// Create element
var e = document.createElement(clone.tag);
delete clone.tag;
// Assign attributes
if (clone.attributes) {
for (var attrib in clone.attributes) {
e.setAttribute(attrib.replace('$', ''), clone.attributes[attrib]);
}
delete clone.attributes;
}
// Create and append children if has
if (clone.children) {
for (var idx in clone.children) {
e.appendChild(this.createElement(clone.children[idx]));
}
delete clone.children;
}
// Assign event handlers
if (clone.events) {
for (var en in clone.events) {
var handler = clone.events[en];
if (handler instanceof Function)
this.addHandler(e, en, handler);
}
delete clone.events
}
// Assign properties
for (var prop in clone) {
e[prop] = clone[prop];
}
return e;
},
addHandler: function (element, eventName, handler) {
// Firefox is first, Of cource after chrome :p
if (element.addEventListener) {
element.addEventListener(eventName, handler, false);
}
else if (element.attachEvent) {
element.attachEvent('on' + eventName, handler);
}
},
extend: function (expando, properties, override) {
if (properties && typeof (properties) == 'object') {
for (var prop in properties) {
var val = properties[prop];
if (!expando[prop] || override)
expando[prop] = val;
}
}
return expando;
}
您可以重寫上面的代碼使用jQuery延長,而不是創建一個新的元素。
使用
Util.createElement({
tag: 'input',
type: 'checkbox',
checked: this.checked,
events: {
change: function(e) { // ... }
}
});
你爲什麼不試試看看發生了什麼! – 2011-09-20 04:51:38
我做到了,但(可能是因爲語法不正確)它沒有工作。 – jym