2011-08-24 37 views
0

请参阅 Accessing Parameters *and* Events in function from jQuery EventjQuery的钻营

我怎样才能改变这种代码,以便$(this)作用就像$(this)在点击事件,而不是返回的完整的HTML文档的?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<html> 
<head> 
<meta http-equiv="Expires" content="Fri, Jan 01 1900 00:00:00 GMT"> 
<meta http-equiv="Pragma" content="no-cache"> 
<meta http-equiv="Cache-Control" content="no-cache"> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
<meta http-equiv="content-language" content="en"> 
<meta name="author" content=""> 
<meta http-equiv="Reply-to" content="@.com"> 
<meta name="generator" content="PhpED 5.2"> 
<meta name="description" content=""> 
<meta name="keywords" content=""> 
<meta name="creation-date" content="09/20/2007"> 
<meta name="revisit-after" content="15 days"> 
<title>Untitled</title> 
<link rel="stylesheet" type="text/css" href="my.css"> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script> 
<script type="text/javascript"> 
function functionToCall(clickedItem) { 
    return function (ev) { 
    // both accessible here 
    alert(ev.type); 
    console.debug(clickedItem); 
    alert(clickedItem.attr('id')); 
    } 
} 


$(document).ready(function() { 
    $("a").live("click", functionToCall($(this))); 
}); 
</script> 
</head> 
<body> 
    <a href='#' id="test">Test</a> 
</body> 
</html> 

回答

1

重构这样的:

function functionToCall(ev) { // ev -> event is passed by jQuery by default 
    var clickedItem = this; // this refers to the element that is clicked 
    // both accessible here 
    alert(ev.type); 
    //console.debug(clickedItem); // this may not work in all browsers. see my fiddle for a failsafe. 

    // failsafe: check if console exists 
    if(window.console && window.console.debug) { console.debug(clickedItem); } 
    alert($(clickedItem).attr('id')); // $() to get jQuery object 
} 

$(document).ready(function() { 
    $("a").live("click", functionToCall); // just need to pass a function reference 
}); 

演示:http://jsfiddle.net/mrchief/ZYGVz/1/

0

尝试是这样的:

$("a").each(function(){ 
    $(this).live("click",functionToCall($(this))); 
}) 
+0

'不需要each'。当你说'$('a')。live(...)'时,jQuery将把click事件绑定到所有'a'元素。 – Mrchief

+0

我们其中一个人误解了这个问题 – Coomie