我希望这个:
$('.iat_map').each(function(i,el) { $(el).html(opt_list); });和这个:
$('.iat_map').html(opt_list);做同样的事情。 但是,当我尝试前者时,它会清除内容而不是用opt_list替换它。 ( .iat_map指的是一堆<selects> .iat_map <selects> )。
如果我在each()内部console.log(opt_list) , console.log(opt_list)预期输出。
是什么赋予了?
做了一个小提琴 。 完全可重复(至少在Chrome 21中)。
I would expect this:
$('.iat_map').each(function(i,el) { $(el).html(opt_list); });And this:
$('.iat_map').html(opt_list);To do the same thing. However, when I try the former, it clears the contents instead of replacing it with opt_list. (.iat_map refers to a bunch of <selects>).
If I console.log(opt_list) inside that each(), it ouputs as expected.
What gives?
Made a fiddle. Perfectly reproducible (in Chrome 21 at least).
最满意答案
问题是opt_list是一个jQuery对象(意味着jQuery将选项放入DOM元素中),当你追加jQuery对象时,DOM元素将从旧位置移除并添加到新位置。
这就是为什么当你使用.each ,你会发现选项只在最后一个选择上。
显然,当你做$('.iat_map').html(opt_list); ,jQuery在追加它们之前克隆DOM元素。
我建议将opt_list变成一个字符串,而不是jQuery对象。
The problem is that opt_list is a jQuery object (meaning jQuery made the options into DOM elements), and when you append jQuery object, the DOM elements are removed from their old spot and added to their new spot.
That's why when you use .each, you'll notice that the options are only on the last select.
Apparently, when you do $('.iat_map').html(opt_list);, jQuery clones the DOM elements before appending them.
I suggest making opt_list into a string, instead of a jQuery object.
jQuery.each和.html的行为不符合预期(jQuery.each and .html not behaving as expected)我希望这个:
$('.iat_map').each(function(i,el) { $(el).html(opt_list); });和这个:
$('.iat_map').html(opt_list);做同样的事情。 但是,当我尝试前者时,它会清除内容而不是用opt_list替换它。 ( .iat_map指的是一堆<selects> .iat_map <selects> )。
如果我在each()内部console.log(opt_list) , console.log(opt_list)预期输出。
是什么赋予了?
做了一个小提琴 。 完全可重复(至少在Chrome 21中)。
I would expect this:
$('.iat_map').each(function(i,el) { $(el).html(opt_list); });And this:
$('.iat_map').html(opt_list);To do the same thing. However, when I try the former, it clears the contents instead of replacing it with opt_list. (.iat_map refers to a bunch of <selects>).
If I console.log(opt_list) inside that each(), it ouputs as expected.
What gives?
Made a fiddle. Perfectly reproducible (in Chrome 21 at least).
最满意答案
问题是opt_list是一个jQuery对象(意味着jQuery将选项放入DOM元素中),当你追加jQuery对象时,DOM元素将从旧位置移除并添加到新位置。
这就是为什么当你使用.each ,你会发现选项只在最后一个选择上。
显然,当你做$('.iat_map').html(opt_list); ,jQuery在追加它们之前克隆DOM元素。
我建议将opt_list变成一个字符串,而不是jQuery对象。
The problem is that opt_list is a jQuery object (meaning jQuery made the options into DOM elements), and when you append jQuery object, the DOM elements are removed from their old spot and added to their new spot.
That's why when you use .each, you'll notice that the options are only on the last select.
Apparently, when you do $('.iat_map').html(opt_list);, jQuery clones the DOM elements before appending them.
I suggest making opt_list into a string, instead of a jQuery object.
发布评论