将外部var传递给jquery函数

时间:2014-02-06 00:01:50

标签: javascript jquery var

HTML文件:

<head>
   //include jQuery
</head>
<body>
    //HTML stuff

    <script type="text/javascript">
    var prd = 'something';
    </script>

    <script type="text/javascript" src="script.js"></script>
</body>

的script.js

$('#select span').click(function(){
    var id = this.id;

    var path = '/scripts/test/sqlgetdata.php?id='+id+'&p='+prd;

    path = encodeURIComponent(path);

    post(path);
});

function post(path){
  //stuff
}

var prd无法将var path包含在$('#select span').click(function(prd) 中。

我也试过了:

{{1}}

没有回调可以解决这个问题吗? 谢谢

1 个答案:

答案 0 :(得分:2)

传递给event.data

$('#select span').click({prd: prd}, function(e){
    var id  = this.id;
    var prd = e.data.prd; // here

    var path = '/scripts/test/sqlgetdata.php?id='+id+'&p='+prd;

    path = encodeURIComponent(path);

    post(path);
});

FIDDLE