Javascript 复选框 检查事件侦听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14544104/
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
Checkbox Check Event Listener
提问by Oliver Kucharzewski
Recently I have been working with the Chrome Plugin API and I am looking to develop a plugin which will make life easier for me for managing a website.
最近,我一直在使用 Chrome 插件 API,我希望开发一个插件,它可以让我更轻松地管理网站。
Now what I wish to do is to fire an event when a certain checkbox is checked. As this website does not belong to me I cannot change the code therefore I am using the Chrome API. One of the main problems is that rather than there being an ID, there is a Name. I was wondering if I could fire the function once the certain checkbox with the 'name' is checked.
现在我想做的是在选中某个复选框时触发一个事件。由于本网站不属于我,我无法更改代码,因此我使用的是 Chrome API。主要问题之一是没有 ID,而是有名称。我想知道一旦选中带有“名称”的特定复选框,我是否可以触发该功能。
回答by thordarson
Assuming you're using this markup:
假设您正在使用此标记:
<input type="checkbox" name="checkbox">
Without jQuery
没有 jQuery
Using the jQuery-like querySelector.
使用类似 jQuery 的querySelector。
var checkbox = document.querySelector("input[name=checkbox]");
checkbox.addEventListener( 'change', function() {
if(this.checked) {
// Checkbox is checked..
} else {
// Checkbox is not checked..
}
});
With jQuery
使用 jQuery
$('input[name=checkbox]').change(function(){
if($(this).is(':checked')) {
// Checkbox is checked..
} else {
// Checkbox is not checked..
}
});
回答by JFK
Since I don't see the jQuerytag in the OP, here is a javascriptonly option :
由于我没有jQuery在 OP 中看到该标签,这里是一个仅使用javascript 的选项:
document.addEventListener("DOMContentLoaded", function (event) {
var _selector = document.querySelector('input[name=myCheckbox]');
_selector.addEventListener('change', function (event) {
if (_selector.checked) {
// do something if checked
} else {
// do something else otherwise
}
});
});
See JSFIDDLE
回答by SabU
If you have a checkbox in your html something like:
如果您的 html 中有一个复选框,例如:
<input id="conducted" type = "checkbox" name="party" value="0">
<input id="conducted" type = "checkbox" name="party" value="0">
and you want to add an EventListener to this checkbox using javascript, in your associated js file, you can do as follows:
并且您想使用 javascript 在此复选框中添加一个 EventListener,在关联的 js 文件中,您可以执行以下操作:
checkbox = document.getElementById('conducted');
checkbox.addEventListener('change', e => {
if(e.target.checked){
//do something
}
});

