简体   繁体   English

为什么这个简单的JavaScript函数不能按我预期的那样工作? 尝试确定是否已选中复选框

[英]Why isn't this simple JavaScript function working as I expect? Trying to determine if a checkbox is checked

I have HTML in the following form: 我有以下形式的HTML:

<div id="filters">
    <ul>
        <li><label class="checkbox"><input type="checkbox" value="" checked data-filter=".one">One</label></li>
        <li><label class="checkbox"><input type="checkbox" value="" checked data-filter=".two">Two</label></li>
        <li><label class="checkbox"><input type="checkbox" value="" checked data-filter=".three">Three</label></li>
        <li><label class="checkbox"><input type="checkbox" value="" checked data-filter=".four">Four</label></li>
        <li><label class="checkbox"><input type="checkbox" value="" checked data-filter=".five">Five</label></li>
        <li><label class="checkbox"><input type="checkbox" value="" checked data-filter=".six">Six</label></li>
    </ul>
</div>

My JavaScript function is as follows: 我的JavaScript函数如下:

<!-- language: lang-js -->
function initFilters()
{
    $('#filters input').each(function(){
        if ($(this).checked) {
            console.log($(this).attr('data-filter')+' is checked');
            addFilter($(this).attr('data-filter'));
        } else {
            console.log($(this).attr('data-filter')+' is unchecked');
            removeFilter($(this).attr('data-filter'));
        };
    });
}

The problem I'm having is that $(this).checked always returns false. 我遇到的问题是$(this).checked总是返回false。

jQuery objects don't have a checked property. jQuery对象没有checked属性。 Try this: 尝试这个:

this.checked

or 要么

$(this).prop("checked")

I find the first way easier to read, and it is certainly more efficient, but some people insist on using jQuery for everything, so... 我发现第一种方法更易于阅读,并且肯定更有效,但是有些人坚持将jQuery用于所有功能,因此...

checked is a property of the DOM element, not of a jQuery object. checked是DOM元素的属性,而不是jQuery对象的属性。

if (this.checked) {

You can also retrieve said property with the .prop jQuery object method: 您还可以使用.prop jQuery对象方法检索所述属性:

if ($(this).prop("checked")) {

However the snippet above creates a new jQuery object and calls a method on it, which is not recommended - it is unnecessary, provides slower performance and takes more typing. 但是,上面的代码段创建了一个新的jQuery对象并在其上调用一个方法,不建议这样做-这是不必要的,它会降低性能,并增加输入次数。 I do also find the native method easier to read. 我也发现本机方法更易于阅读。

.prop is more appropriate when working with a set of elements or passing a selector instead of a DOM element reference. 当使用一组元素或传递选择器而不是DOM元素引用时, .prop更合适。

Though, choose whichever you find more readable and maintainable, as both work just fine for your use case. 不过,请选择任何您觉得更易读和可维护的方式,因为两者都适合您的用例。

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

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