Không thể đặt từ khóa this
từ JavaScript. Nó được JavaScript tự động tạo ra và "luôn đề cập đến" chủ sở hữu "của hàm mà chúng ta đang thực thi, hay đúng hơn là đối tượng mà một hàm là một phương thức".
— http://www.quirksmode.org/js/this.html
Bạn có một vấn đề trong mã của mình (cố gắng đặt tên cho tham số của hàm submit_form() cho điều này). Tuy nhiên, cách mã của bạn được đặt ra không làm cho nó rõ ràng cho dù bạn đang có ý định để vượt qua dọc theo neo nhấp vào bọc như một đối tượng jQuery hoặc như là nút DOM cho neo.
$(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
}
});
Trên một lưu ý chủ yếu là không liên quan, có thể bạn sẽ muốn một trong hai return false;
hoặc sử dụng event.preventDefault() để giữ cho trang từ sau href
trên neo được nhấp. Bạn có thể làm điều đó như sau:
$(document).ready(function() {
$('.nav a').click(function(event) {
event.preventDefault();
// And now do what you want the click to do
});
});
Bạn đã làm đúng cách. Chỉ cần đổi tên biến trong 'function submit_form (this) {}' thành một cái gì đó khác như 'function submit_form (element) {}'. –
Hãy sử dụng javascript theo cách nó được dự định sử dụng (không cần phải chuyển ngữ cảnh thành tham số): 'submit_form.call (this)', 'submit_form.apply (this)', hoặc thậm chí sử dụng jQuery nếu đó là điều duy nhất bạn hiểu: 'jQuery.proxy (submit_form, this)' –