它发生是因为,
Chrome 和可能的 Opera 会自动对对象属性进行排序
所以你的 JSON 也是for
循环排序的。
var json = {"":"","1":"Test #1","2":"Test #2"};
for(var i in json)
console.log(i);
/* Result : 1 2 (null) */
演示
解决方案1:
如果您将索引更改为不会排序的字符串。
var json = {"":"","t1":"Test #1","t2":"Test #2"};
for(var i in json)
console.log(i);
/* Result : (null) t1 t2 */
演示
解决方案2:
更换插件
这是与数组一起使用的已编辑插件代码,
/*
* Remote Chained - jQuery AJAX(J) chained selects plugin
*
* Copyright (c) 2010-2011 Mika Tuupola
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
*/
(function($) {
$.fn.remoteChained = function(parent_selector, url, options) {
return this.each(function() {
/* Save this to self because this changes when scope changes. */
var self = this;
var backup = $(self).clone();
/* Handles maximum two parents now. */
$(parent_selector).each(function() {
$(this).bind("change", function() {
/* Build data array from parents values. */
var data = {};
$(parent_selector).each(function() {
var id = $(this).attr("id");
var value = $(":selected", this).val();
data[id] = value;
});
$.getJSON(url, data, function(json) {
var selectedVal;
/* Clear the select. */
$("option", self).remove();
/* Add new options from json. */
for (var key in json.options) {
var k = json.options[key];
/* This sets the default selected. */
if ("selected" == k.name) {
selectedVal = k.value;
continue;
}
var option = $("<option />").val(k.value).append(k.name);
$(self).append(option);
}
/* Loop option again to set selected. IE needed this... */
$(self).children().each(function() {
if ($(this).val() == selectedVal) {
$(this).attr("selected", "selected");
}
});
/* If we have only the default value disable select. */
if (1 == $("option", self).size() && $(self).val() === "") {
$(self).attr("disabled", "disabled");
} else {
$(self).removeAttr("disabled");
}
/* Force updating the children. */
$(self).trigger("change");
});
});
/* Force updating the children. */
$(this).trigger("change");
});
});
};
/* Alias for those who like to use more English like syntax. */
$.fn.remoteChainedTo = $.fn.remoteChained;
})(jQuery);
要使用这个更新的插件,你应该使用这个 JSON 格式,
{
"options" : [
{ "value" : "", "name" : ""},
{ "value" : "1", "name" : "Test #1"},
{ "value" : "2", "name" : "Test #2"},
]
}
如果你想设置一个默认的选中项(例如“Test #1”被选中),那么你可以这样做,
{
"options" : [
{ "value" : "", "name" : ""},
{ "value" : "1", "name" : "Test #1"},
{ "value" : "2", "name" : "Test #2"},
{ "value" : "1", "name" : "selected"}
]
}
我怎样才能使用这个编辑过的插件?
只需清除所有代码,/js/chained.js
然后粘贴新代码。