Which of the following is better?
1) Create the element on 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 the element, only change it's html on each loop
Note: This does not work, It requires
.clone() as 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 reviewing all the answers/comments here is the final function. Any more 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;
};