我有一个问题,我想启用/显示选项,如果该选项与“ColumnCode”同名并且“IsRow”为真。除此之外,该选项被禁用/隐藏。
我尝试了下面的代码,但没有成功。
var model = {
Rows: $('#Rows')
};
var columns =
[{"ColumnCode":"CollateralType","IsRow":true},
{"ColumnCode":"CollectorUnit","IsRow":true}];
_.each(columns, function (col) {
model.Rows.find('option').each(function () {
if (this.value != col['ColumnCode'] || (this.value == col['ColumnCode'] && !col['IsRow']))
$(this).attr('disabled', true);
});
});
这是选择元素:
<select name="Rows[]" id="Rows">
<option value="AccountNo">Account No</option>
<option value="CollateralType">Collateral Type</option>
</select>
有人可以指导一下吗?
最佳答案
您应该彻底翻转该循环,首先遍历选项,然后遍历数组,否则您的选项将不断重新设置,或者最终可能始终被禁用。
您可能还想添加类似于 <option value="none">...please select</option>
的默认选项值以确保在所有内容都被禁用的情况下不会选择任何内容。
var model = {
Rows: $('#Values') // had to change this from #Row for demo to work
};
var columns = [
{"ColumnCode": "CollateralType", "IsRow": true}, // change this to see different results
{"ColumnCode": "CollectorUnit", "IsRow": true}
];
// enable option if option has the same name as "ColumnCode" and "IsRow" is true
model.Rows.find('option').each(function (index, option) {
var matchFound = false;
var isRow = false;
_.each(columns, function (col) {
if (option.value == col['ColumnCode']) {
matchFound = true;
isRow = col['IsRow']
return false;
}
});
if(matchFound && !isRow || !matchFound){
$(this).attr('disabled', true); //jQuery pre 1.6
//$(this).prop('disabled', true); // jQuery v1.6 or later
}
});
如果您动态发生这种情况并且需要重置所有禁用的属性,只需执行 model.Rows.find('option').removeAttr('disabled')
或者如果您使用的是 jQuery 1.6 或更高版本,请使用 model.Rows.find('option').prop('disabled', false)
在开始循环之前。
DEMO - 仅启用列表中且 isRow 设置为 true 的选项
<小时/>关于javascript - 禁用选项选择 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23808052/