문제

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