我会这样做...
function assert( outcome, description ) {
var assrt = $('#assert');
if (!assrt || !assrt.length) {
assrt = $('<ul>',{id:"assert"}).appendTo('body');
}
assrt.append('<li>', {className:outcome ? 'hide' : 'alert-danger', text:description});
}
或者,如果该assert
元素打算供后续调用使用,我可能会使用闭包来维护调用之间的引用......
var assert = (function() {
var assrt = $('#assert');
return function( outcome, description )
if (!assrt || !assrt.length) {
assrt = $('<ul>',{id:"assert"}).appendTo('body');
}
assrt.append('<li>', {className:outcome ? 'hide' : 'alert-danger', text:description});
};
}());
您可以通过返回几个函数来扩展它...
var assert = (function() {
var assrt = $('#assert');
function verify_assert_container() {
if (!assrt || !assrt.length) {
assrt = $('<ul>',{id:"assert"}).appendTo('body');
}
}
return {
add: function( outcome, description )
verify_assert_container();
assrt.append('<li>', {className:outcome ? 'hide' : 'alert-danger', text:description});
},
empty: function() {
verify_assert_container();
assrt.empty();
},
sort: function() {
verify_assert_container();
// use sorting algorithm to reorder the LI elements
},
destroy: function() {
if (assrt) {
assrt.remove();
assrt = null;
}
}
};
}());
并像这样使用它...
assert.add('foo', 'bar');
assert.empty();
assert.destroy();