Javascript 在 input.checked=true/false _without_ jQuery 上触发一个事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10637801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:15:48  来源:igfitidea点击:

Fire an event on input.checked=true/false _without_ jQuery

javascripthtml

提问by jwl

Consider the following code (http://jsfiddle.net/FW36F/1/):

考虑以下代码(http://jsfiddle.net/FW36F/1/):

<input type="checkbox" onchange="alert(this.checked)">
<button onclick="document.getElementsByTagName('input')[0].checked=!document.getElementsByTagName('input')[0].checked;">toggle</button>

If you click the checkbox, you get an alert telling you if it's checked or not. Great. However, if you click the toggle button, the checkbox changes it's checked state but the onchange event is NOT fired.

如果您单击该复选框,您会收到一条警报,告诉您它是否已选中。伟大的。但是,如果您单击切换按钮,复选框会更改其选中状态,但不会触发 onchange 事件。

Essentially, the onchange for a checkbox only fires if the user actually clicks the checkbox, notif the checkbox is changed via JavaScript. This is be true in IE, FF, and Chrome. It appears that this behavior is to specification also.

本质上,复选框的 onchange 仅在用户实际单击复选框时触发,而不是通过 JavaScript 更改复选框时触发。这在 IE、FF 和 Chrome 中是正确的。看来这种行为也符合规范。

However, I really need some kind of event to fire if, for any reason, the checkbox's checked state changes. Is this possible?

但是,如果出于某种原因,复选框的选中状态发生更改,我确实需要触发某种事件。这可能吗?

Oh yeah, and jQuery is not allowed. And please no setTimeout/setInterval based solutions either...

哦,是的,不允许使用 jQuery。并且请不要基于 setTimeout/setInterval 的解决方案...

Update:Also, I should make it clear that the code above is for illustration only. In the real code, we need to ensure the state of the checkbox is checked or unchecked -- not just toggle it. Perhaps this would be better code to illustrate that:

更新:另外,我应该明确指出上面的代码仅用于说明。在实际代码中,我们需要确保复选框的状态是选中或未选中的——而不仅仅是切换它。也许这会是更好的代码来说明:

<input type="checkbox" onchange="alert(this.checked)">
<button onclick="document.getElementsByTagName('input')[0].checked=true;">check</button> 
<button onclick="document.getElementsByTagName('input')[0].checked=false;">un check</button>

Moreover, there may be code in other areas we don't fully control, which might do a simple .checked=true/false -- we'd like to make sure we see that also.

此外,可能还有我们无法完全控制的其他区域的代码,这可能会执行简单的 .checked=true/false - 我们希望确保我们也能看到这一点。

采纳答案by Juan Mendes

The existing answers work just fine, even with your update. Just be smart about it and don't call click if you don't need to. Also, please don't use inline JS. That was OK 10 years ago.

现有的答案工作得很好,即使你的update。只是聪明点,如果你不需要,不要打电话给点击。另外,请不要使用内联JS。10 年前还可以。

<input type="checkbox" onchange="alert(this.checked)">
<button id='check'>check</button> 
<button id='uncheck'>uncheck</button>

document.getElementById('check').onclick = function() {
   if (!this.checked) {
      this.click();
   }
}

If you need to be modified when a script changes the value, in Firefox, you can use https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/watch

如果需要在脚本更改值时进行修改,在 Firefox 中可以使用https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/watch

Example here http://jsfiddle.net/PPuZ8/

这里的例子http://jsfiddle.net/PPuZ8/

// In FF $ is a shortcut for document.getElementById
// It doesn't fire when set from the UI, you have to use a regular handler for that
$('cb').watch("checked", function(){
   console.log('Checked state changed from script', arguments);
   return true;
});

For IE you can use onpropertychangehttp://msdn.microsoft.com/en-us/library/ie/ms536956(v=vs.85).aspx(Thanks to jivings for the reminder)

对于 IE,您可以使用onpropertychangehttp://msdn.microsoft.com/en-us/library/ie/ms536956(v=vs.85) .aspx(感谢 jivings 的提醒)

Example: http://jsfiddle.net/PPuZ8/1/

示例:http: //jsfiddle.net/PPuZ8/1/

document.getElementById('cb').onpropertychange = function() {    
    if (event.propertyName == 'checked') {
       console.log('Checked state changed onproperty change');    
    }
};

For other browsers, you have to poll using setInterval/setTimeout

对于其他浏览器,您必须使用 setInterval/setTimeout 进行轮询

回答by Sampson

Have the toggle button actually clickthe checkbox:

让切换按钮实际单击复选框:

<input type="checkbox" onchange="alert(this.checked)">
<button onclick="document.getElementsByTagName('input')[0].click()">
  toggle
</button>

If you wanted any change to the checkbox to inform you of its new position, then I would create a global method for changing the value of the checkbox, and deal with it as a proxy:

如果您希望对复选框进行任何更改以通知您其新位置,那么我将创建一个全局方法来更改复选框的值,并将其作为代理处理:

<script>
function toggleCB( state ) {
  var cb = document.getElementById("cb");
  arguments.length ? cb.checked = state : cb.click() ;
  return cb.checked;
}
</script>
<input id="cb" type="checkbox" />
<input type="button" onClick="alert( toggleCB(true) )" value="Check" />
<input type="button" onClick="alert( toggleCB(false) )" value="Uncheck" />
<input type="button" onClick="alert( toggleCB() )" value="Toggle" />?????????????????????????????????????????????????????????????????????????????????????????????????????????????????

Now anytime you set or toggle the checkbox, you'll get the checked state back.

现在,无论何时设置或切换复选框,您都会恢复选中状态。

One last thing, I would avoid using the onClickattribute, and instead bind the click events up from within your JavaScript.

最后一件事,我会避免使用该onClick属性,而是从 JavaScript 中绑定点击事件。

回答by Jivings

Use click()

click()

<button onclick="document.getElementsByTagName('input')[0].checked=!document.getElementsByTagName('input')[0].click();">toggle</button>

回答by Sachin Nayak

oninput is the event you need to handle ... https://developer.mozilla.org/en/DOM/DOM_event_reference/input

oninput 是您需要处理的事件... https://developer.mozilla.org/en/DOM/DOM_event_reference/input