简体   繁体   中英

jQuery Crashes on .live(“keyup”)

I have some code here:

$(document).ready(function() {
$("#querybox").live("keyup", function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) {
       $("#querybox").blur();
    }
    else {
        search(document.getElementById('querybox').value);
    }

    /*if (document.getElementById('querybox').value == "") {
        $("center").removeHighlight();  
    }*/
});
});

that detects a keyUp and uses it to search something. The problem is: when the #querybox is backspaced to the point where it is empty, the entire page crashes and I get the "Awwww, Snap!" message from Google Chrome.

I am using jQuery v1.7.2

Thx a million!

EDIT

I should also point out that the search() function highlights text in the body (notice the commented section). I am using the highlight plugin...


Search Fn:

function search(query) {
    $("center").removeHighlight();
    $(".paragraph").highlight(query);
    $(".highlight").each(function (index) {
        $(this).attr("id", "tmpforgoToByClassScrollhighlight" + index);
    });
}

Try using .on(...) instead:

$("#querybox").on("keyup", function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    var queryBox = this;
    if (code === 13) {   // PRESSED ENTER
       queryBox.blur();
    }
    else {
        search(queryBox.val());
    }
});

After your update:

You might want to look better into how you do your search functiom.

Cache some of those jQuery elements so you do not keep selecting them over and over on each keyup.

Also, I am not going through all of the .highlight code, but there probably is a bug in there that does not allow for an empty string, and that is why the website is causing the browser to crash.

You should use .delegate() instead

$(document).ready(function() {
//It will be a good advice to replace body with a parent element of #querybox
$("body").delegate("#querybox","keyup", function(e) {
 var code = (e.keyCode ? e.keyCode : e.which);
  if (code == 13) {
    $("#querybox").blur();
  }
  else {
    search(document.getElementById('querybox').value);
  }

  /*if (document.getElementById('querybox').value == "") {
    $("center").removeHighlight();  
   }*/
 });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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