问题
Using jquery is it better to create a DOM element like this:-
function create(options)
{
$('<form action="' + options.action + '"></form>');
}
Or like this:
function create(options)
{
$form = $('<form></form>');
$form.attr('action',options.action);
}
This may be a matter of opinion. I feel that the second way gives more clarity but I suspect it is less efficient...
回答1:
jQuery can create object as following code
$form = $('<form>', {action: 'my action'});
class is a reserved word in IE and needs to be quoted. See full list of reserved words: Reserved Keywords in Javascript
回答2:
Check this to find out for your self.
Note higher is better (OPS/Sec = operations per second = how many times per second the given code executes)
And the test winner in every other browser than Opera:
var form = document.createElement("form"),
$form = $(form);
form.action = options.action;
NOTE:
the native method will be even faster if you don't need a jQuery object:
var form = document.createElement("form");
form.action = options.action;
回答3:
I always do the second one.
function create(options)
{
$form = $('<form></form>');
$form.attr('action',options.action);
}
I prefer this method simply because it find it more readable.
回答4:
Never hurts to optimize...until it does...you could use straight up JS:
function create(options)
{
var newform = document.createElement('form');
newform.setAttribute('action',options.action);
}
Aside from that it's negligible as mentionned above, whatever is easier to read for you...i.e. option 2
回答5:
Unless you are running this function many times, any performance difference will be negligible. So I would always go with the clearest, easiest to update solution (i.e. the second one.)
回答6:
Not sure about the actual underlining code of jquery and cannot tell which one has better performance.
Anyway as I can imagine, in the first case jquery will parse attributes anyway and sets values to them, so there should not be big performance difference.
So I think the first solution is more convenient if it contains a lot of html code, otherwise I will prefer second one.
来源:https://stackoverflow.com/questions/9415166/best-way-to-create-new-dom-elements