Best way to create new DOM elements [closed]

ぐ巨炮叔叔 提交于 2020-02-26 08:58:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!