我需要启用禁用的下拉菜单并从json更改值。当我的程序有<select></select><select></select>
时
我的意思是连续选择它工作正常,但当它之间有元素时它不会。
索引页的代码:
<ul>
<li>
<label>Item 1</label>
<select name="item1" id="item1" class="update">
<option value="">Select Item1</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</li>
<li>
<label>Item 2</label>
<select name="item2" id="item2" class="update" disabled="disabled">
<option value="">Select Item2</option>
/*output based on item1*/
</select>
</li>
<li>
<label>Item 3</label>
<select name="item3" id="item3" class="update" disabled="disabled">
<option value="">Select Item3</option>
/*output based on item2*/
</select>
</li>
在索引(以及jquery)中加载的脚本:
var formObject = {
run : function(obj) {
if (obj.val() === '') {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
} else {
var id = obj.attr('id');
var v = obj.val();
jQuery.getJSON('/test/mod/update.php', { id : id, value : v }, function(data) {
if (!data.error) {
obj.next('.update').html(data.list).removeAttr('disabled');
} else {
obj.nextAll('.update').html('<option value="">----</option>').attr('disabled', true);
}
});
}
}
};
$(function() {
$('.update').live('change', function() {
formObject.run($(this));
});
});
我知道我需要改变
obj.next('.update').html(data.list).removeAttr('disabled');
但无法弄清楚。
此外,这适用于jquery 1.6.4但不适用于1.9.1我需要更改哪个部分以更新代码以与最新的jquery兼容?
答案 0 :(得分:3)
而不是使用.removeAttr('disabled')
使用.prop('disabled', false)
。自1.6以来,.prop
作为更新元素属性的方法受到青睐,但在1.7之后更多
答案 1 :(得分:2)
你应该像这样
替换obj.next('.update').html(data.list).removeAttr('disabled');
与
obj.parent().next().children().removeAttr('disabled');
jsfiddle:http://jsfiddle.net/habo/7vMw8/
答案 2 :(得分:1)
jQuery 1.7中不推荐使用.live()
函数,并在jQuery 1.9中将其删除。
您可以改为使用.on()
:
$(document.body).on('change', '.update', function() {
formObject.run($(this));
});
使用.on()
时,最有效的方法是使用要为其调用处理程序的元素的最近祖先。因此,您可以使用document.body
元素,而不是使用<ul>
。如果该元素具有“id”属性会更容易。
为了处理不是兄弟姐妹的<select>
元素,我建议更改以下内容:
obj.nextAll('.update').html(...
obj.next('.update').html(...
对此:
obj.closest('li').nextAll().find('.update').html(...
obj.closest('li').next().find('.update').html(...
当然,您也应该使用.prop()
启用/禁用,如@Explosion Pills所示。