带有recur类的DropDownList遍历设置索引为0的实现问题
问题描述
我拥有一组带有recur类的DropDownList,期望在如下自定义的DisableFields函数中根据条件将它们的索引设置为0,但当前代码无法正常运行,请问可行的实现方式是什么?
原代码
function DisableFields(disable) { if (disable) { $('.recur').prop('disabled', true); $('.recur').each(function (index, obj) { obj.index(0); }); } else { $('.recur').prop('disabled', false); } }
解决方案
问题出在each循环里的obj.index(0):这里的obj是原生DOM元素,不是jQuery对象,原生下拉框元素并没有index()方法。要设置下拉框的选中索引为0,有两种简单的实现方式:
方式1:使用原生DOM的selectedIndex属性
直接操作原生元素的selectedIndex属性,这是最直接高效的方式:
function DisableFields(disable) { if (disable) { $('.recur').prop('disabled', true).each(function (index, obj) { obj.selectedIndex = 0; }); } else { $('.recur').prop('disabled', false); } }
方式2:转为jQuery对象后设置属性
把obj转为jQuery对象,使用prop方法设置selectedIndex:
function DisableFields(disable) { if (disable) { $('.recur').prop('disabled', true).each(function () { $(this).prop('selectedIndex', 0); }); } else { $('.recur').prop('disabled', false); } }
可以看到两种方式都把设置disabled和选中索引的操作合并成了链式调用,避免重复选择DOM元素,提升了代码效率。
内容的提问来源于stack exchange,提问作者stonypaul
相关产品推荐
相关产品推荐

