【问题标题】:Get a message if checkbox selected only for the first time如果复选框仅第一次被选中,则会收到一条消息
【发布时间】:2017-03-01 14:42:29
【问题描述】:

如果一个复选框仅第一次被选中,我想执行一个函数。有可能吗?

通过使用:

this.on('buuttonCheckBox:set', function(){
  //do the work
 })

或

this.on('buuttonCheckBox:change', function(){
  //do the work
 })

或使用 Jquery:

  $('#checkbox1').click(function() {
    if (!$(this).is(':checked')) {
        return confirm("Are you sure?");
    }
});

【问题讨论】:

    标签: javascript jquery checkbox


    【解决方案1】:

    假设该框开始时未选中,请使用one(不是one,不是on)。它附加一个事件处理程序,它会在第一个事件上删除。

    尝试勾选,然后取消勾选,然后勾选:

    $("#cb").one("click", function() {
      console.log("First and only notification");
    });
    <label><input id="cb" type="checkbox"> Click me</label>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    当然,也可以保持跟踪; jQuery 的data 是一种方便的方法:

    $("#cb").on("click", function() {
      console.log("Clicked");
      var $this = $(this);
      if (this.checked && !$this.data("seen")) {
        $this.data("seen", true);
        console.log("The one and only notification");
      }
    });
    <label><input id="cb" type="checkbox"> Click me</label>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    【讨论】:

      【解决方案2】:

      实现一个布尔变量,如果它已经被检查过,它将保留信息。

      var wasChecked = false;
      $('#checkbox1').click(function() {
          if (!wasChecked) {
              alert("Are you sure?");
              wasChecked = true;
          }
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <input type='checkbox' id='checkbox1'>

      【讨论】:

        【解决方案3】:

        为change事件添加一个EventListener函数,并在函数内部删除EventListener

        function one(){
          document.getElementById('checkbox1').removeEventListener('change',one);
          return confirm("Are you sure");
        }
        document.getElementById('checkbox1').addEventListener('change',one);
        &lt;input type="checkbox" id="checkbox1" value="Check" /&gt;

        【讨论】:

          猜你喜欢
          • 2020-08-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多