如果使用" ctrl + a + backspace"

时间:2016-12-19 20:53:16

标签: javascript jquery html

我正在使用jQuery和输入字段进行一些简单的div过滤。它正在工作,但如果我使用"删除输入,它就不会检测到它是空的。 Ctrl + a + backspace ",换句话说,如果我选择所有文本并将其删除。是什么原因造成的?

如果使用键盘命令,则不会将div重新排序为默认值,但如果退格每个字符,则会恢复正常。

我就是这样做的:

$('#brandSearch').keyup(function() {
    var valThis = $(this).val().toLowerCase();
    if (valThis.length == 0) {
        $('.card').show();
    } else {
        $('.card').each(function() {
            var text = $(this).text().toLowerCase();
            (text.indexOf(valThis) >= 0) ? $(this).parent().show(): $(this).parent().hide();
        });
    };
});

2 个答案:

答案 0 :(得分:1)

似乎工作正常:



$('#brandSearch').keyup(function() {
    var valThis = $(this).val().toLowerCase();
    if (valThis.length == 0) {
        $('.card').show();
      console.log("input is empty");
    } else {
      console.log("input is not empty");                  
        $('.card').each(function() {
            var text = $(this).text().toLowerCase();
            (text.indexOf(valThis) >= 0) ? $(this).parent().show(): $(this).parent().hide();
        });
    };
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="brandSearch">
&#13;
&#13;
&#13;

答案 1 :(得分:1)

处理空字符串的item.encode('utf8', 'surrogatepass')块未显示if块隐藏的相同元素。 else块调用else,但.parent()块不调用。{/ p>

因此,if案例会显示或隐藏每个else元素的,但.card案例会显示if元素本身 - 没有取消隐藏他们的父母。请参阅我添加到代码中的注释(为了清晰起见,我还在.card中重新格式化了条件表达式):

else

由于听起来非空字符串的情况正常,因此只需在$('#brandSearch').keyup(function() { var valThis = $(this).val().toLowerCase(); if (valThis.length == 0) { // Show all of the .card elements $('.card').show(); } else { $('.card').each(function() { var text = $(this).text().toLowerCase(); // Show or hide the *parent* of this .card element text.indexOf(valThis) >= 0 ? $(this).parent().show() : $(this).parent().hide(); }); }; }); 块中添加.parent()即可与其他块匹配:

if

在这种情况下,熟悉浏览器的调试工具可以节省大量时间。 $('#brandSearch').keyup(function() { var valThis = $(this).val().toLowerCase(); if (valThis.length == 0) { // Show the parent of each .card element $('.card').parent().show(); } else { // Show or hide the parent of each .card element $('.card').each(function() { var text = $(this).text().toLowerCase(); text.indexOf(valThis) >= 0 ? $(this).parent().show() : $(this).parent().hide(); }); }; }); .show()方法操纵DOM,通过使用DOM检查器,您可以轻松查看隐藏和显示哪些元素。

事实上,作为一项学习练习,我建议您通过返回原始代码暂时解决错误,然后打开DOM检查器,看看它是如何揭示问题的。当你在那里时,也可以试用JavaScript调试器和其他工具。

如果您使用Chrome,则此处为introduction to the Chrome Developer Tools。其他浏览器也有类似的工具和文档。