链接到我的小提琴jsFiddle
我正在尝试使用jQuery为select选项构建选项并将它们添加到2个不同的选项中,这是我的标记和代码:
var selectValues = [{ "ownerid": " ", "name": " "}, { "ownerid": 123, "name":"Tom"}, { "ownerid": 345, "name": "Dick"}, { "ownerid": 888, "name": "Harry"}];
$.each(selectValues, function(key, value) {
var myoption = $("")
.attr("value", value.ownerid)
.text(value.name);
$('#select1').append(myoption);
$('#select2').append(myoption);
});
然而,'myoption'仅附加到1选择而不是另一个.
问题:如何在不声明相同变量的情况下将其附加到两者?
干杯!
这是预期的行为,您需要创建.clone()
对象并将append()
其创建为第二个元素.
$.each(selectValues, function(key, value) { var myoption = $("") .attr("value", value.ownerid) .text(value.name); $('#select1').append(myoption); //Append cloned object $('#select2').append(myoption.clone()); });
var selectValues = [{ "ownerid": " ", "name": " "}, { "ownerid": 123, "name":"Tom"}, { "ownerid": 345, "name": "Dick"}, { "ownerid": 888, "name": "Harry"}];
$.each(selectValues, function(key, value) {
var myoption = $("")
.attr("value", value.ownerid)
.text(value.name);
$('#select1').append(myoption);
$('#select2').append(myoption.clone());
});