【问题标题】:Apply the action only to this element on the page仅将操作应用于页面上的此元素
【发布时间】:2021-07-01 03:12:33
【问题描述】:

请告诉我如何将displayCount 函数绑定到当前的filter_item$('.filter_item').each(function() { 中的所有内容都可以正常工作,但 function displayCount() { 对页面上的所有 filter_item 运行。

jQuery(function($) {
    
    var count = 0;
    
    $('.filter_item').each(function() {
        
        count = $(this).find('input[type=checkbox].jet-checkboxes-list__input:checked').length;
        displayCount();  
        
        $(this).find('input[type=checkbox].jet-checkboxes-list__input').bind('click' , function(e, a) {   
            if (this.checked) {
                count += a ? -1 : 1;
                } else {
                count += a ? 1 : -1;
            }
            displayCount();
        });
        
    });
    
    function displayCount() {
        if (count == 0) {
            $('.count').hide();
            } else {
            $('.count').show();
            $('.count').text(count);
        }
    }
}); 

【问题讨论】:

  • 你能显示你的html代码吗?

标签: jquery function this each


【解决方案1】:
$('.count').hide();

选择文档中具有类计数的每个元素。所以是的,它会改变每个条目。如果你只想改变你得到的每个,你需要将 $(this) 转移到你的 displayCount() 函数

 function displayCount(element) {
    if (count == 0) {
        element.hide();
        } else {
        element.show().text(count);
    }
}

然后这样称呼它

$('.filter_item').each(function() {
    
    var element = $(this).find('input[type=checkbox].jet-checkboxes-list__input:checked');
    count = element.length;
    displayCount(element);  
    
    ....
    
});

【讨论】:

  • 感谢您的回复。我还没有真正理解它,但它似乎没有帮助。我需要将displayCount 函数绑定到页面上的每个.filter_item
【解决方案2】:

也许有人会需要)

jQuery(function($) {

    
    $('.filter_item').each(function() {
        let that = this;
        let count = 0;
        count = $(this).find('input[type=checkbox].jet-checkboxes-list__input:checked').length;
        displayCount.call(that, count);  
        
        $(this).find('input[type=checkbox].jet-checkboxes-list__input').bind('click' , function(e, a) {  
            if (this.checked) {
                count += a ? -1 : 1;
                } else {
                count += a ? 1 : -1;
            }
            displayCount.call(that, count);
        });
    });
    
    function displayCount(count) {
        if (count == 0) {
            $('.count', this).hide();
            } else {
            $('.count', this).show().text(count);
        }
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 2013-02-22
    相关资源
    最近更新 更多