简体   繁体   English

复选框 检查事件侦听器

[英]Checkbox Check Event Listener

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.由于本网站不属于我,我无法更改代码,因此我使用的是 Chrome API。 One of the main problems is that rather than there being an ID, there is a Name.主要问题之一是没有 ID,而是有名称。 I was wondering if I could fire the function once the certain checkbox with the 'name' is checked.我想知道一旦选中带有“名称”的特定复选框,我是否可以触发该功能。

Short answer: Use the change event.简短回答:使用change事件。 Here's a couple of practical examples.这里有几个实际的例子。 Since I misread the question, I'll include jQuery examples along with plain JavaScript.由于我误读了这个问题,我将包括 jQuery 示例和纯 JavaScript。 You're not gaining much, if anything, by using jQuery though.但是,通过使用 jQuery,您并没有获得太多(如果有的话)。

Single checkbox单个复选框

Using querySelector .使用querySelector

 var checkbox = document.querySelector("input[name=checkbox]"); checkbox.addEventListener('change', function() { if (this.checked) { console.log("Checkbox is checked.."); } else { console.log("Checkbox is not checked.."); } });
 <input type="checkbox" name="checkbox" />

Single checkbox with jQuery带有 jQ​​uery 的单个复选框

 $('input[name=checkbox]').change(function() { if ($(this).is(':checked')) { console.log("Checkbox is checked..") } else { console.log("Checkbox is not checked..") } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" name="checkbox" />

Multiple checkboxes多个复选框

Here's an example of a list of checkboxes.这是复选框列表的示例。 To select multiple elements we use querySelectorAll instead of querySelector .要选择多个元素,我们使用querySelectorAll而不是querySelector Then use Array.filter and Array.map to extract checked values.然后使用Array.filterArray.map提取选中的值。

 // Select all checkboxes with the name 'settings' using querySelectorAll. var checkboxes = document.querySelectorAll("input[type=checkbox][name=settings]"); let enabledSettings = [] /* For IE11 support, replace arrow functions with normal functions and use a polyfill for Array.forEach: https://vanillajstoolkit.com/polyfills/arrayforeach/ */ // Use Array.forEach to add an event listener to each checkbox. checkboxes.forEach(function(checkbox) { checkbox.addEventListener('change', function() { enabledSettings = Array.from(checkboxes) // Convert checkboxes to an array to use filter and map. .filter(i => i.checked) // Use Array.filter to remove unchecked checkboxes. .map(i => i.value) // Use Array.map to extract only the checkbox values from the array of objects. console.log(enabledSettings) }) });
 <label> <input type="checkbox" name="settings" value="forcefield"> Enable forcefield </label> <label> <input type="checkbox" name="settings" value="invisibilitycloak"> Enable invisibility cloak </label> <label> <input type="checkbox" name="settings" value="warpspeed"> Enable warp speed </label>

Multiple checkboxes with jQuery jQuery 的多个复选框

 let checkboxes = $("input[type=checkbox][name=settings]") let enabledSettings = []; // Attach a change event handler to the checkboxes. checkboxes.change(function() { enabledSettings = checkboxes .filter(":checked") // Filter out unchecked boxes. .map(function() { // Extract values using jQuery map. return this.value; }) .get() // Get array. console.log(enabledSettings); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label> <input type="checkbox" name="settings" value="forcefield"> Enable forcefield </label> <label> <input type="checkbox" name="settings" value="invisibilitycloak"> Enable invisibility cloak </label> <label> <input type="checkbox" name="settings" value="warpspeed"> Enable warp speed </label>

Since I don't see the jQuery tag in the OP, here is a javascript only option :由于我在 OP 中没有看到jQuery标签,这里是一个仅使用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 JSFIDDLEJSFIDDLE

If you have a checkbox in your html something like:如果您的 html 中有一个复选框,例如:

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

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM