如果数组为空,则禁用按钮,并在添加项目时启用



我有一个数组,其中包含一些复选框id号,当用户单击表中的某些复选框时,这些复选框id将被添加。如果数组为空,我想禁用一个按钮,当它有一些项目时启用它。

var ids = [];
$('#Table tbody').on('click', '.checkbox', function () {
var idx = $.inArray($(this).attr("id"), ids);
if (idx == -1) {
ids.push($(this).attr("id"));
} else {
ids.splice(idx, 1);
}
});

监视数组并检查元素是否已添加到id数组或是否已降到0以启用/禁用按钮的最佳方法是什么?

<input class="btn disabled" type="submit" name="submit" id="btnsubmit" value="Submitselected"/>

单击复选框时,您已经运行了函数(也许change事件更适合您(-现在只需修改按钮上的disabled道具:

$("#btnsubmit").prop("disabled", ids.length === 0);

我想在这里扩展@PeterRadar的答案,因为这实际上是一个很好的建议。基本上,这里的想法是将关注的数组封装在代理中,然后使用该代理基本上"订阅"更改。将这个建议与这个答案和@tymeJV结合起来,得到的代码看起来像这样的片段:

var array = [true];
var updateButtonVisibility = function() {
$("#test").prop("disabled", array.length === 0);
}
$( document ).ready(function() {
var arrayChangeHandler = {
get: function(target, property) {
updateButtonVisibility();
console.log('getting property ', property);
return target[property];
},
set: function(target, property, value, receiver) {
target[property] = value;
updateButtonVisibility();
console.log('setting property ' + property + ' length is ' + array.length);
return true;
}
}
var wrappedArray = new Proxy(array, arrayChangeHandler )

$("#add").click(function() {wrappedArray.push(true);});
$("#subtract").click(function() {wrappedArray.pop();});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button id="test" type="submit">HELLO</button>
<button id="add" type="submit">Add</button>
<button id="subtract" type="submit">Subtract</button>
</body>


为什么要这样做

以这种方式使用代理(wrappedArray对象(允许您在使用其setter和getter向该对象写入/从中读取该对象时运行自定义行为。在您的示例中,意味着禁用按钮的功能在对象更改时运行,而不仅仅是在单击另一个ui组件时。这意味着按钮的禁用/启用状态的实现不与任何特定的UI组件绑定。只要通过此wrappedArray使用访问权限,无论是什么原因导致设置/获取,您的禁用/启用状态都将以您想要的方式更新。

最新更新