This is an example on CodePen.

Here's the code anyway:

HTML:

<div contenteditable="true" id="mydiv"></div>

jQuery:

$(function () {
  $("#mydiv").keydown(function (evt) {
    if (evt.which == 13) {
      evt.preventDefault();
      alert('event fired');  
    }
  });
});

Why won't the evt.preventDefault() method work?

有帮助吗?

解决方案

The preventDefault call just keeps the default event handler from running. If you want to skip any code after the point where you have evt.preventDefault(), put a return false after it.

$(function () {
    $("#mydiv").keydown(function (evt) {
        if (evt.which == 13) {
            return false; // <-- now event doesn't bubble up and alert doesn't run
            alert('event fired');  
        }
    });
});

Also, as mentioned by squint, you can use stopPropagation and preventDefault to achieve the same effect.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top