TMP*_*guy 11 javascript jquery this
如何将$ this(self关键字)传递给Jquery中的函数
$(document).ready(function() {
$('.nav a').click(function() {
var direction = $(this).attr("name");
submit_form($(this))
});
function submit_form(this)
{
// do some stuff with 'this'
}
});
Run Code Online (Sandbox Code Playgroud)
Jos*_*h K 17
将其包装成$()一个jQuery对象.你会想要做类似的事情
submit_form(this);
function submit_form(obj)
{
// Work with `obj` as "this"
// Or wrap it in $() to work with it as jQuery(this)
}
Run Code Online (Sandbox Code Playgroud)
该this关键字不能在JavaScript中进行设置.它由JavaScript自动生成,并且"始终引用我们正在执行的函数的"所有者",或者更确切地说,指向函数是"的方法".
- http://www.quirksmode.org/js/this.html
您的代码中有一个问题(尝试将submit_form()函数的参数命名为this).但是,您的代码布局方式并不清楚您是否打算传递包含为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
}
});
Run Code Online (Sandbox Code Playgroud)
在一个大多数不相关的注释中,您可能想要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
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16935 次 |
| 最近记录: |