jQuery - 如何在单击函数中包含变量

时间:2014-12-17 20:57:18

标签: jquery

我有以下功能:

getAccessPointArray()
    .done(function(array) {

        var obj = JSON.parse(array);

        for ( i = 0; i < obj.data.length; i++ ) {

            var identifier = obj.data[i]['identifier'];
            var url = obj.data[i]['url'];

            $( "." + identifier ).click(function() {
                alert("This is the URL: " + url );   
            });

        }

    }
);

我的阵列:

obj = array( 'data' =>
['url' => url 1, 'identifier' => ident 1] , 
['url' => url 2, 'identifier' => ident 2]
);

似乎正在发生的是,url是在第一次传递时设置的,但是在第二次传递时它不会覆盖第一个URL ...

所以我的输出是:

This is the URL: url 1
This is the URL: url 1

不确定我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

您需要关闭i变量。你可以用IIFE来做这件事

(function(i){
 var identifier = obj.data[i]['identifier'];
 var url = obj.data[i]['url'];

 $( "." + identifier ).click(function() {
  alert("This is the URL: " + url );   
 });
}(i)

这是一个Stack Snippet Demo

&#13;
&#13;
var obj = {
 data : [
  { 
   url : 'world',
   identifier : 'hello'
  },
  {
   url : 'polo',
   identifier : 'marco'
  }
 ]
};
for ( var i = 0; i < obj.data.length; i++ ) {
 (function(i){
  var identifier = obj.data[i]['identifier'];
  var url = obj.data[i]['url'];

  $( "." + identifier ).click(function() {
    alert("This is the URL: " + url );   
  });
 })(i)
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div class="hello">
   Hello  
  </div>
  <div class="marco">
   Marco 
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可能已经尝试过,但以防万一。在分配到click()

后尝试重置URL和标识符
var identifier;
var url;
for ( i = 0; i < obj.data.length; i++ ) {
     identifier = obj.data[i]['identifier'];
     url = obj.data[i]['url'];

    $( "." + identifier ).click(function() {
         alert("This is the URL: " + url );   
    });

    identifier = '';
    url = '';
}