我有一个包含大量下拉菜单的页面,每个下拉菜单旁边都有一个按钮。当页面最初加载时,我希望禁用所有按钮,如果对特定下拉列表进行了更改,则应启用其相应的按钮。
我已经为此获得了以下代码,但我需要知道如何遍历所有下拉菜单和按钮,以便我可以概括它。
$(document).ready(function () {
//disable all buttons
function disableAllButtons () {
$(':input[type=button]').attr("disabled", "true");
}
disableAllButtons();
//enable button when drop down changes
$(':input[name=sNewPKvalue1]').focus(function() {
disableAllButtons();
$(':input[name=Update0]').removeAttr("disabled");
})
//enable button when drop down changes
$(':input[name=sNewPKvalue2]').focus(function() {
disableAllButtons();
$(':input[name=Update1]').removeAttr("disabled");
})
////.....question?
});
问题
如果我有12个下拉菜单和12个按钮
如何遍历名称为sNewPKvalue[1-12]
的所有下拉菜单以及名称为Update[0-11]
的所有按钮
答案 0 :(得分:2)
我不推荐循环。只需使用选择器来选择所需的元素并执行相应的操作。我的第一个想法是为按钮分配一个CSS类并下拉你正在谈论的列表。然后你可以简单地做这样的事情:
$('.dropDown').focus(function(){
$(".ddlButton").attr("disabled", "true");
$(this).closest('.ddlButton').removeAttr("disabled");
});
答案 1 :(得分:1)
我会做类似的事情:
$.each([1, 12], function(index, value) {
var valmin = val - 1;
$(':input[name=sNewPKvalue'+value+']').focus(function() {
disableAllButtons();
$(':input[name=Update'+valmin+']').removeAttr("disabled");
})
});
我没有测试过这个,但你应该明白这个想法;)
答案 2 :(得分:0)
你可以这样做。
for (var i = 0; i < 12; i++)
{
$(':input[name=sNewPKvalue'+(i+1)+']').focus(function() {
disableAllButtons();
$(':input[name=Update'+i+']').removeAttr("disabled");
})
}
或者
$(':input[name^=sNewPKvalue]').focus(function() {
disableAllButtons();
$(':input[name=Update'+(Number(this.name.match(/[0-9]+/))-1)+']').removeAttr("disabled");
})
答案 3 :(得分:0)
你可以做的是做一个for循环。
for(var i = 1; i <= 12; i++) {
$("select[name='sNewPKvalue"+i+"']").doSomething();
}
for(var i = 1; i <= 11; i++) {
$(":button[name='Update"+i+"']").doSomething();
}