質問

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