开发者

jQuery .each conflicts with jQuery select append

开发者 https://www.devze.com 2023-03-04 09:55 出处:网络
I\'m simply adding options to a select tag (aka dropdown list).Why doesn\'t the second loop work?I will have to spend some time debugging jQuery, but if until I spend too much time, I figured I\'d pos

I'm simply adding options to a select tag (aka dropdown list). Why doesn't the second loop work? I will have to spend some time debugging jQuery, but if until I spend too much time, I figured I'd post this and move on to a new task.

Here's my key/value pair array:

var map = { "10": "ten", "11": "eleven", "12": "twelve" };

This doesn't work:

    jQuery.each(map, function(key, val) {
        jQuery(this.Elements.DDLTest).append(jQuery("<option></option>").val(key).text(val)); 
    });

This works:

    for (key in map) {
        jQuery(this.Elements.DDLTest).append(jQuery("<option></option>").val(key).text(map[key]));
   开发者_如何学运维 }


In jQuery.each the this variable within the callback contains the current element, not whatever value it had in your outer scope.

Try this:

var that = this;
jQuery.each(map, function(key, val) {
    jQuery(that.Elements.DDLTest).append(jQuery("<option></option>").val(key).text(val)); 
});


The this in your first example has changed context; the this refers to the map reference, and since it doesnt have an Elements property, it fails.

0

精彩评论

暂无评论...
验证码 换一张
取 消