La parola chiave this
non può essere impostata in JavaScript. Viene generato automaticamente da JavaScript e "si riferisce sempre al" proprietario "della funzione che stiamo eseguendo, o meglio, all'oggetto che una funzione è un metodo di".
— http://www.quirksmode.org/js/this.html
avete uno problema nel codice (cercando di nominare il parametro della funzione submit_form() per questo). Tuttavia, il modo in cui il codice è disposto non rende chiaro se intendi passare l'ancora cliccato avvolto come un oggetto jQuery o come nodo DOM per l'ancora.
$(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
}
});
Su una nota per lo più estranei, probabilmente si vorrà o return false;
o utilizzare per event.preventDefault() per mantenere la pagina dal seguito della href
sull'ancoraggio che è stato cliccato. Puoi farlo come segue:
$(document).ready(function() {
$('.nav a').click(function(event) {
event.preventDefault();
// And now do what you want the click to do
});
});
Lo fai già correttamente. Basta rinominare la variabile in 'function submit_form (this) {}' con qualcos'altro come 'function submit_form (element) {}'. –
Si prega di utilizzare javascript nel modo in cui è stato progettato per essere utilizzato (non è necessario passare il contesto come parametro): 'submit_form.call (this)', 'submit_form.apply (this)', o anche usare jQuery se è l'unica cosa capisci: 'jQuery.proxy (submit_form, this)' –