2017-03-01 48 views
-2

如果仅在首次选中复选框时才想执行某个功能。可能吗?如果仅在第一次选中复选框,则会显示一条消息

使用:

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?"); 
    } 
}); 

回答

2

假设该框未启动,请使用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>

1

实现一个布尔变量将保持信息,如果它已经被选中或不。

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'>

1

添加事件侦听功能变化事件和在函数内部,取出事件侦听

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

相关问题