我怎么能在数组中附加不同的值?

时间:2015-04-19 18:14:47

标签: jquery arrays function push

我试图通过点击<来追加城市名称。李>元素并将它们添加到数组但我被卡住了,这是我到目前为止所得到的:

<div id='cities'>pick cities: 
   <div id='csffs'></div>
   <ul>
       <li>San francisco</li>
       <li>Palo Alto</li>
       <li>San Diego</li>
       <li>Los Angeles</li>
       <li>Toledo</li>
   </ul>
</div>

$('li').on('mouseup', function() {
        var city = $(this).text();
        var bunch_of_cities = ['New York','Cleveland','Port Clinton','Toledo'];
    if($.inArray(city,bunch_of_cities) > -1){
    //if found, not added up to the array
        city = null;
    }else{
    // if not found, then add it up to the array
        bunch_of_cities.push(city);
    }
        $("#csffs").html(free_to.join());


});

Jsfiddle

我面临的问题是,我需要能够添加超过1个城市,而不是像我上面留下的演示一样:

即:

New York,Cleveland,Port Clinton,Toledo [Whichever city was clicked]

我想要这样的事情:

New York,Cleveland,Port Clinton,Toledo,San francisco, Palo Alto,....so forth and so on

随意更改位或给我一个更好的方法来做到这一点,当然感谢您的时间!!!

PD:我一直在学习自己的代码,请原谅上面的草率代码

3 个答案:

答案 0 :(得分:2)

您在mouseup函数中声明了var bunch_of_cities,因此每次调用该函数时都会重新创建它。你必须声明它超出了该功能的范围。例如

var bunch_of_cities = ['New York','Cleveland','Port Clinton','Toledo'];

$('li').on('mouseup', function() {
        var city = $(this).text();
    if($.inArray(city,bunch_of_cities) > -1){
    //if found, not added up to the array
        city = null;
    }else{
    // if not found, then add it up to the array
        bunch_of_cities.push(city);
    }
        $("#csffs").html(free_to.join());
});

答案 1 :(得分:1)

您需要在全局范围内声明初始数组bunch_of_cities。原因是,每次修改此数组时,所有函数都可以使用它。

您的代码用于在每次点击事件中初始化数组。

var bunch_of_cities = ['New York', 'Cleveland', 'Port Clinton', 'Toledo'];
$('li').on('mouseup', function () {
     var city = $(this).text();

     if ($.inArray(city, bunch_of_cities) > -1) {
         //if found not added up to the array
         city = null;
     } else {
         // if not found, then add it up to the array
         bunch_of_cities.push(city);
     }
     $("#ok").html(bunch_of_cities.join());
});

另外,我认为您不需要if(...),请使用此

if ($.inArray(city, bunch_of_cities) == -1) {
     // if not found, then add it up to the array
     bunch_of_cities.push(city);
}

Fiddle (基于你的小提琴)

答案 2 :(得分:1)

我改变了一点。 您尝试附加数据的数组应该是全局的。

看看:

var bunch_of_cities = ['New York', 'Cleveland', 'Port Clinton', 'Toledo'];
$('li').on('mouseup', function() {
  var city = $(this).text();
  if ($.inArray(city, bunch_of_cities) > -1) {
    //if found not added up to the array
    city = null;
  } else {
    // if not found, then add it up to the array
    bunch_of_cities.push(city);
  }
  $("#ok").html(bunch_of_cities.join());
});