Discuss / JavaScript / 作业:这是不是个BUG?

作业:这是不是个BUG?

Topic source

_wsdzl

#1 Created at ... [Delete] [Delete and Lock User]

成功代码

var sa = $('label.selectAll'), invs = $('a.invertSelect'), boxes = $('input[name=lang]');
function is_sa (){
    return boxes.map(function(){return this.checked}).get().indexOf(false) === -1;
}
function check (){
    sa.find('[type=checkbox]').prop('checked', is_sa());
    (is_sa()?$('span.deselectAll'):$('span.selectAll')).show();
    (!is_sa()?$('span.deselectAll'):$('span.selectAll')).hide();
}
boxes.click(check);
sa.click(function(){
    boxes.prop('checked', sa.find('[type=checkbox]').prop('checked'));
    check();
})
invs.click(function(){
    boxes.each(function(){this.checked = !this.checked;});
    check();//此处若改成下面写法则程序出错,单击“反选”不能达到设定效果
});

BUG代码

var sa = $('label.selectAll'), invs = $('a.invertSelect'), boxes = $('input[name=lang]');
function is_sa (){
    return boxes.map(function(){return this.checked}).get().indexOf(false) === -1;
}
/*原来的代码
function check (){
    sa.find('[type=checkbox]').prop('checked', is_sa());
    (is_sa()?$('span.deselectAll'):$('span.selectAll')).show();
    (!is_sa()?$('span.deselectAll'):$('span.selectAll')).hide();
}
boxes.click(check);*/
//改成传入匿名函数
boxes.click(function(){
    sa.find('[type=checkbox]').prop('checked', is_sa());
    (is_sa()?$('span.deselectAll'):$('span.selectAll')).show();
    (!is_sa()?$('span.deselectAll'):$('span.selectAll')).hide();
}

);
sa.click(function(){
    boxes.prop('checked', sa.find('[type=checkbox]').prop('checked'));
    //原来写法check();
    boxes.click();//此处boxes.click();可以执行,下面却不可以
})
invs.click(function(){
    boxes.each(function(){this.checked = !this.checked;});
    //原来写法
    //check();
    //改成这样下面执行出问题
    boxes.click();//??????????????????????????????????
    /*或者这样写也不会出错
    sa.find('[type=checkbox]').prop('checked', is_sa());
    (is_sa()?$('span.deselectAll'):$('span.selectAll')).show();
    (!is_sa()?$('span.deselectAll'):$('span.selectAll')).hide();
    直接把boxes.click()代码复制粘贴到这里
    */
});

难道程序指定执行一次某个绑定事件不能在jquery的遍历方法map()和each后? 这是jquery的bug吗?

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

请牢记:

jQuery没有bug

并不是说jQuery真的没有bug,而是作为初学者,99.99%出错的可能性都是自己的代码

同理,你在学Python、Java这些语言时也要牢记:

解释器没有bug

系统库没有bug

编译器没有bug

JVM没有bug

三年以上开发经验的才有资格怀疑

_wsdzl

#3 Created at ... [Delete] [Delete and Lock User]

感谢老师回答。 能麻烦老师帮看下代码吗,不知道下面那种写法问题出在哪里。


  • 1

Reply