Ý nghĩa của hàm e.predefault

The following example demonstrates how invalid text input can be stopped from reaching the input field with preventDefault(). Nowadays, you should usually use native HTML form validation instead.

HTML

Here’s the form:

<div class=”container”> <p>Please enter your name using lowercase letters only.</p> <form> <input type=”text” id=”my-textbox”> </form>
</div>

CSS

We use a little bit of CSS for the warning box we’ll draw when the user presses an invalid key:

.warning { border: 2px solid #f39389; border-radius: 2px; padding: 10px; position: absolute; background-color: #fbd8d4; color: #3b3c40;
}

JavaScript

And here’s the JavaScript code that does the job. First, listen for keypress events:

var myTextbox = document.getElementById(‘my-textbox’);
myTextbox.addEventListener(‘keypress’, checkName, false);

The checkName() function, which looks at the pressed key and decides whether to allow it:

function checkName(evt) { var charCode = evt.charCode; if (charCode != 0) { if (charCode < 97 || charCode > 122) { evt.preventDefault(); displayWarning( “Please use lowercase letters only.” + “\n” + “charCode: ” + charCode + “\n” ); } }
}

The displayWarning() function presents a notification of a problem. It’s not an elegant function but does the job for the purposes of this example:

var warningTimeout;
var warningBox = document.createElement(“div”);
warningBox.className = “warning”; function displayWarning(msg) { warningBox.innerHTML = msg; if (document.body.contains(warningBox)) { window.clearTimeout(warningTimeout); } else { myTextbox.parentNode.insertBefore(warningBox, myTextbox.nextSibling); } warningTimeout = window.setTimeout(function() { warningBox.parentNode.removeChild(warningBox); warningTimeout = -1; }, 2000);
}

Result

Chúng ta thương thấy 3 method này và có thể dẫn dến bối rối và nhầm lẫn giữa chúng:

  • Event.preventDefault()
  • Event.stopPropagation()
  • Event.stopImmediatePropagation()

Tóm tắt

Đầu tiên hãy xem tóm tắt tại MDN nhé

Ý nghĩa của hàm e.predefault

  • preventDefault: Huỷ bỏ event nếu nó có thể huỷ mà không dừng sự lan rộng(propagation) của event tới phần khác.
  • stopPropagation Ngăn chặn sự lan rộng của sự kiện hiện tại tới thằng khác.
  • stopImmediatePropagation ngăn chặn những listeners cũng đang đang lắng nghe cùng event được gọi.

Event.preventDefault

Hãy nhìn vào mãi ví dụ ở dưới. Chúng ta sẽ thấy việc click vào submit button trên form sẽ gửi nội dung của form tới chỗ xử lý. Event.preventDefault là cách hoàn hảo để không cho gửi form khi nhấn vào button submit.

<

form

id

=

myForm

action

=

/my-handling-form-page

method

=

post

>

<

div

>

<

label

for

=

name

>

Name:

</

label

>

<

input

type

=

text

id

=

name

/>

</

div

>

<

div

>

<

label

for

=

mail

>

E-mail:

</

label

>

<

input

type

=

email

id

=

mail

/>

</

div

>

<

div

>

<

label

for

=

msg

>

Message:

</

label

>

<

textarea

id

=

msg

>

</

textarea

>

</

div

>

<

div

class

=

button

>

<

button

type

=

submit

>

Send your message

</

button

>

</

div

>

</

form

>

$

(

‘#myForm’

)

.

on

(

‘submit’

,

function

(

e

)

{

e

.

preventDefault

(

)

;

}

)

;

Event.preventDefault sẽ đảm bảo rằng form không bao giờ được gửi, và nó đã giành được quyền kiểm soát và ngăn chặn sự kiện đó khi click. Đó là những gì chúng ta đã làm.

Event.stopPropagation

stopPropagation để đảm bảo chắc chắn rằng event không lan rộng nữa. Hãy xem ví dụ ở dưới:

<

div

class

=

container

>

<

a

href

=

#

class

=

element

>

Click Me!

</

a

>

</

div

>

$

(

‘.container’

)

.

on

(

‘click’

,

function

(

e

)

{

console

.

log

(

‘container was clicked’

)

;

}

)

;

$

(

‘.element’

)

.

on

(

‘click’

,

function

(

e

)

{

e

.

preventDefault

(

)

;

console

.

log

(

‘element was clicked’

)

;

}

)

;

Bây giờ nếu bạn click link và trước đó đã mở console bạn sẽ thấy:

“element was clicked”

“container was clicked”

Bây giờ hãy thêm Event.stopPropagation:

$

(

‘.container’

)

.

on

(

‘click’

,

function

(

e

)

{

console

.

log

(

‘container was clicked’

)

;

}

)

;

$

(

‘.element’

)

.

on

(

‘click’

,

function

(

e

)

{

e

.

preventDefault

(

)

;

e

.

stopPropagation

(

)

;

console

.

log

(

‘element was clicked’

)

;

}

)

;

Và click lại. Đây sẽ là cái bạn thấy:

“element was clicked”

Event.stopImmediatePropagation

Với 2 methods ở trên đã giúp bạn khoảng 90% các trường hợp cần thiết phải xử lí với events. Nhưng hãy tìm hiểu tiếp mothod cuối này nhé

Ý nghĩa của hàm e.predefault

Chúng ta sẽ bắt đầu với markup tương tự ở trên, và thêm vào một class. Một cái là item mà tất cả các anchors sẽ nhận, và một cái riêng chỉ cho markup ở đây. Nó rất quan trọng để giúp code ví dụ này hoặt động.

<

div

class

=

“container”

>

<

a href

=

“#”

class

=

“item element”

>

Click Me

!

<

/

a

>

<

/

div

>

Và chúng sẽ thêm Event.stopPropagation mothod mà chúng ta đã tìm hiểu ở phần trước.

$

(

‘.item’

)

.

on

(

‘click’

,

function

(

e

)

{

console

.

log

(

‘an item was clicked’

)

;

}

)

;

$

(

‘.element’

)

.

on

(

‘click’

,

function

(

e

)

{

e

.

preventDefault

(

)

;

e

.

stopPropagation

(

)

;

console

.

log

(

‘element was clicked’

)

;

}

)

;

Bây giờ hãy hãy xem có gì ở console khi click nhé.

“an item was clicked”

“element was clicked”

Vấn đề ở đây là .item và .element được xếp đồng hạng trên DOM. Nó không lan tràn lên phần tử trên như ví dụ trước đó. Và vì khi click cả 2 action gắn trên .element và .item sẽ chạy cùng lúc, bạn không thể dừng lan rộng(propagation) như bạn mong muốn.

Đây chính là cơ hội để xử dụng stopImmediatePropagation!

$

(

‘.element’

)

.

on

(

‘click’

,

function

(

e

)

{

e

.

preventDefault

(

)

;

e

.

stopImmediatePropagation

(

)

;

console

.

log

(

‘element was clicked’

)

;

}

)

;

$

(

‘.item’

)

.

on

(

‘click’

,

function

(

e

)

{

console

.

log

(

‘an item was clicked’

)

;

}

)

;

Điêu quan trọng ở đây để ngăn chặn sự lan rộng tới cùng hạng của event trong DOM là đặt stopImmediatePropagation ở ngay khai báo lệnh đầu tiên về action lắng nghe event click trong code của bạn. Như ở dây là chuyển các method từ .item lên .element.

Và thành của của chúng ta đây:

“element was clicked”

Bài tham khảo