Creating a repeating jquery element

Which of the following is better?
1) Create an element in each loop

$(obj).children('option').each(function(){
  var item = $('<div />')
    .html($(this).text())
    .append(plus)
    .addClass('ui-widget-content ui-state-default')
    .hover(
      function(){$(this).addClass('ui-state-hover')}, 
      function(){$(this).removeClass('ui-state-hover');}
    );
    $(list).append(item);
});


2) Create an element, just change its html to each cycle
Note. This does not work, it requires .clone(), as shown below.
var item = $('<div />')
  .addClass('ui-widget-content ui-state-default')
  .hover(
    function(){$(this).addClass('ui-state-hover')}, 
    function(){$(this).removeClass('ui-state-hover');});

$(obj).children('option').each(function(){
  $(item).html($(this).text()).append(plus);  
  $(list).append(item);
});


Update:
So, after considering all the answers / comments, there is a final function here. Any improvements?
function create_list(obj) {
  var list = $('<div />')
    .attr('id','keyword_unselect').addClass('ui-widget')
    .delegate("div", "mouseenter mouseleave", function() {
      $(this).toggleClass('ui-state-hover');
    });

  var plus = $('<div />').addClass('ui-icon-plus');

  var item = $('<div />')
    .append(plus)
    .addClass('ui-widget-content ui-state-default');

  $(obj).children('option').each(function(){    
    item.clone(true)
      .prepend(this.text)
      .appendTo(list);
  });
  return list;
};
+3
source share
2 answers

The first in this case, although the second will be better, but currently it has a different effect (the element moves every time).

Create it once and .clone()add it, for example:

 var item = $('<div />', { 'class': 'ui-widget-content ui-state-default' })
                  .hover(function(){$(this).addClass('ui-state-hover')}, 
                         function(){$(this).removeClass('ui-state-hover');});

$(obj).children('option').each(function(){
  $(list).append(item.clone(true).html(this.text).append(plus));
});

Here you can try here .

.text <option> , , , - .


, .delegate(), mouseneter mouseleave:

$(list).delegate("div", "mouseenter mouseleave", function() {
    $(this).toggleClass('ui-state-hover');
});

var item = $('<div />', { 'class': 'ui-widget-content ui-state-default' });    
$(obj).children('option').each(function(){
  $(list).append(item.clone().html(this.text).append(plus));
});

.

+1

, , , , .

, .clone() item, , .

, plus , .prepend() .

, .appendTo() .append() list.

var item = $('<div />')
  .addClass('ui-widget-content ui-state-default')
  .append(plus)
  .hover(
    function(){$(this).addClass('ui-state-hover')}, 
    function(){$(this).removeClass('ui-state-hover');});

$(obj).children('option').each(function(){
  item.clone(true)
      .prepend( $.text([this]) )
      .appendTo(list);  
});
+1

Source: https://habr.com/ru/post/1764674/


All Articles