1

我有一个数组,其中包含一些复选框 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"/>
4

2 回答 2

2

单击复选框时,您已经运行了该功能(尽管该change事件可能更适合您)-disabled现在只需修改按钮上的道具:

$("#btnsubmit").prop("disabled", ids.length === 0);
于 2018-07-30T15:29:52.603 回答
1

我想在这里扩展@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 组件。只要通过 this 使用访问wrappedArray,无论是什么原因导致设置/获取,您的禁用/启用状态都会以您想要的方式更新。

于 2018-07-30T16:16:31.303 回答