你還沒有真正納入夠你的代碼對我來說,能找出你想要做什麼 - 但這裏的術語的解釋,你問:
event.preventDefault()
event.stopPropagation()
event.stopImmediatePropagation()
3個jQuery函數在阻止事件和處理程序執行方面略有不同。
return false;
在另一方面可以說是一個基本的編程約定,存在於許多編程漢語語言和的Javascript是這些語言中的一種。
或類似的與<form>
元素,如果你需要防止的形式被提前提交。一個例子是對的不完整的表格表單驗證,在這種情況下,你可以做這樣的事情
function validateForm() {
var subject = document.forms["contact"]["subject"].value;
var message = document.forms["contact"]["message"].value;
var name = document.forms["contact"]["name"].value;
var email = document.forms["contact"]["email"].value;
if (subject == null || subject == "" || subject == " " || message == null || message == "" || message == " " || name == null || name == "" || name == " " || email == null || email == "" || email == " ") {
$('#form-incomplete').html('<strong>Please fill out all the fields before sending email</strong>');
return false;
}
}
你經常會看到return false;
這樣使用:作爲if
conidition的結果(即if (some_condition_is_present) { return false; // i.e. halt your function }
和這絕對是什麼從你的代碼中缺少如果我理解你正確地你會想嘗試像
<a class="some_class" href="http://some-other-website.com">WEBSITE LINK</a>
那麼其他地方的頁面上,你可以有這樣一個腳本:
$("a.some_class").on("click", function(e) {
e.preventDefault();
// now the link won't go to http://some-other-website.com
// but you can still bind other behavour to the element such as alert
// console log or trigger another function
});
或
$("a.some_class").on("click", function(e) {
e.stopPropogation();
// now the link won't go to http://some-other-website.com
// and the other elements of the DOM aren't aware that it's been clicked
// but we can still bind other behaviour like we could:
alert("user not directed to http://some-other-website.com");
});
或
$("a.some_class").on("click", function(e) {
e.stopPropogation();
// now the link won't go to http://some-other-website.com
// and the other elements of the DOM aren't aware that it's been clicked
// but we can't bind other behaviour to the element.
// If we try:
alert("user not directed to http://some-other-website.com");
// it no longer alerts
});
或
$("a.some_class").on("click", function(e) {
if (!foo) {
return false; // if our variable is undefined or null we can directly exit our function without executing any code
} else {
a.href = foo;
$("a.some_class").trigger("click"); // however, if our variable is defined we use that variable's value to change where the href of the <a> element will redirect the user's browswer
}
});
'返回FALSE'做到這一點jQuery中,你需要使用一個事件的方法,香草JS。 – Teemu
@Teemu-jQuery標籤,問題文本中沒有jQuery,代碼中沒有,因此如何在這裏獲得jQuery? – RobG
@RobG這是「有人說返回false是event.stopPropagation()和event.preventDefault()的唯一解釋。」「 – Teemu