实现这一目标的最佳方法是什么?这也应该(自然地)禁用鼠标向上事件的默认值,默认情况下会更改复选框的值。
答案 0 :(得分:1)
HTML:
<input type="checkbox" name="mycheckbox" value="checkme" />
JavaScript的:
var checkbox = document.getElementsByName("mycheckbox")[0];
checkbox.addEventListener("mousedown", function(e){
if(!e){ e = window.event; }
//Stop checkbox from being toggled on IE9 & Other Browsers
if(e.stopPropagation){ e.stopPropagation(); }
//Stop checkbox from being toggled on IE8 and Lower
else{ e.cancelBubble = true; }
//Toggle the checkbox yourself instead
checkbox.checked = (checkbox.checked) ? true : false;
//And you can also change the value of the checkbox
checkbox.value="newvalue";
});
答案 1 :(得分:1)
如何在复选框上设置点击功能
$(document).on('click', '#myCheckBoc', function(e){
e.preventDefault();
alert($(this).val()); //initial value
$(this).val('15');
alert($(this).val()); //changed value
});
<强> FIDDLE 强>
答案 2 :(得分:0)
通过一些假设,我提出了这个有效的代码片段:
如果您需要别的东西,请告诉我。
document.getElementById("checkboxValue").innerHTML = document.getElementById("checkbox").value;
document.getElementById("checkbox").onmousedown = function(e){
e.preventDefault();
alert("Changing checkbox value...");
this.value = "value2";
document.getElementById("checkboxValue").innerHTML = "value2";
};
<input type="checkbox" id="checkbox" value="value1" />
<p>Checkbox Value: <span id="checkboxValue"></span></p>
答案 3 :(得分:0)
checkbox.onclick = (e) => e.preventDefault(); // disable built-in behaviour
checkbox.onmousedown = (e) => {
checkbox.checked = !checkbox.checked;
// if you need it to still fire 'change' event:
checkbox.dispatchEvent(new Event('change'));
}
其他答案要么已停用错误事件(e.preventDefault()
应在[{1}}上调用,而不在click
上),要么错过mousedown
部分。