简体   繁体   English

jQuery的咖喱

[英]jquery currying

Please see Accessing Parameters *and* Events in function from jQuery Event 请参阅从jQuery Event函数中访问参数*和*事件

How can I change this code so $(this) acts like $(this) in a click event instead of returning the complete html document? 如何更改此代码,使$(this) $(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>

Refactor it like this: 像这样重构它:

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
 }); 

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

Try something like this: 尝试这样的事情:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM