的this
關鍵字不能在JavaScript中進行設置。它是由JavaScript自動生成的,並且「總是指向我們正在執行的函數的」所有者「,或者更確切地說,是指函數是」的方法「的對象。
— http://www.quirksmode.org/js/this.html
你在你的代碼的一個問題(試圖命名submit_form()函數的這個參數)。然而,你的代碼的佈局方式並沒有說明你是否打算傳遞包裝爲jQuery對象的點擊的錨或作爲錨的DOM節點。
$(document).ready(function() {
$('.nav a').click(function() {
$anchor = $(this); // Capture the jQuery-wrapped anchor for re-use; 'this' is an anchor because it matched $('.nav a')
var direction = $anchor.attr("name"); // $variable_name is a standard pattern in jQuery to indicate variables that are jQuery-wrapped instead of DOM objects
submit_form_jquery($anchor); // Providing versions of submit_form function for passing either jQuery-wrapped object or DOM object
submit_form_dom(this); // Pick the one you prefer and use it
});
function submit_form_jquery($my_anchor) { // Function with well-named parameter expecting a jQuery-wrapped object
// do some stuff with '$my_anchor'
// $my_anchor here is assumed to be a jQuery-wrapped object
}
function submit_form_dom(anchor) { // Function named expecting a DOM element, not a jQuery-wrapped element
// do some stuff with 'anchor'
// anchor here is assumed to be a DOM element, NOT wrapped in a jQuery object
}
});
在一個大部分是不相關的筆記,你可能會想要麼return false;
或使用event.preventDefault()從下面的被點擊的錨href
保持頁面。你可以這樣做,如下:
$(document).ready(function() {
$('.nav a').click(function(event) {
event.preventDefault();
// And now do what you want the click to do
});
});
你已經做得正確。只需將'function submit_form(this){}'中的變量重命名爲'function submit_form(element){}''。 – 2010-07-30 17:01:54
請以使用javascript的方式使用(不需要傳遞上下文作爲參數):'submit_form.call(this)','submit_form.apply(this)',或者甚至使用jQuery,如果這是唯一的你明白了:'jQuery.proxy(submit_form,this)' – 2012-10-09 22:12:26