Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

Jquery 1.10.2 $.each function not working

Ok, first let me describe my HTML.

I have a select list name and ID as upload_Gcat that has three options. I then have a select list name and ID as upload_album. What I want is as upload_Gcat is changed upload_album changes its options according to what was selected. I have gotten my query to work as far as removing the old. But when it reaches my $.each function it does not work.

I have tried various different code lines inside the $.each function, even tried the bad debug way of alerts, no alert showed up while inside of $.each.

var new_options = new Array();
new_options["album1"] = "album1";
new_options["album2"] = "album2";
new_options["album3"] = "album3";

var select = $('upload_album');
if(select.prop){
    var options = select.prop('options');
}
else{
    var options = select.attr('options');
}

$('option', select).remove();

$.each(new_options, function(key, value) {
    options[options.length] = new Option(value, value);
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may try this (Use an object instead of array, JavaScript doesn't support associative array)

var new_options = {}; // an empty object
new_options["album1"] = "album1";
new_options["album2"] = "album2";
new_options["album3"] = "album3";

var select = $('#upload_album').empty();
$.each(new_options, function(key, value) {
    var newOption = $('<option/>', {'value':key, 'text':value});
    select.append(newOption);
});

DEMO. Also, check Working with objects on MDN.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...