简体   繁体   English

Jquery array.push() 不起作用

[英]Jquery array.push() not working

I have been trying to add variables from a dropdown into an array using Jquery array.push() function but for some odd reason it is not working.我一直在尝试使用 Jquery array.push() 函数将下拉列表中的变量添加到数组中,但由于某些奇怪的原因它不起作用。 Following is the jsFiddle link: http://jsfiddle.net/dKWnb/3/以下是 jsFiddle 链接: http : //jsfiddle.net/dKWnb/3/

JavaScript : JavaScript :

$("#test").live("click",function() {
       var myarray = new Array();
        myarray.push($("#drop").val());
        alert(myarray);
});

HTML HTML

<Select name=drop id=drop>
    <option value=1>1</option>
    <option value=2>2</option>
</select>
<input type=button name=test id=test value=test>

Your HTML should include quotes for attributes : http://jsfiddle.net/dKWnb/4/ 您的HTML应包含属性引用: http//jsfiddle.net/dKWnb/4/

Not required when using a HTML5 doctype - thanks @bazmegakapa 使用HTML5文档类型时不需要 - 谢谢@bazmegakapa

You create the array each time and add a value to it ... its working as expected ? 您每次都创建数组并为其添加一个值...它按预期工作?

Moving the array outside of the live() function works fine : 将数组移到live()函数之外的工作正常:

var myarray = []; // more efficient than new Array()
$("#test").live("click",function() {
        myarray.push($("#drop").val());
        alert(myarray);
});

http://jsfiddle.net/dKWnb/5/ http://jsfiddle.net/dKWnb/5/

Also note that in later versions of jQuery v1.7 -> the live() method is deprecated and replaced by the on() method. 另请注意,在jQuery v1.7的更高版本中 - >不推荐使用live()方法,并将其替换为on()方法。

Your code alerts the current value of the dropdown for me, showing that it has properly pushed into the array. 您的代码会警告我下拉列表的当前值,表明它已正确推送到数组中。

Are you wanting to keep old values and append? 你想保留旧的价值观并附加吗? You're recreating the array each time, meaning that the old value gets clobbered. 您每次都在重新创建数组,这意味着旧值会被破坏。

Here's some updated code: 这是一些更新的代码:

var myarray = [];
$("#test").click(function() {
    myarray.push($("#drop").val());
    alert(myarray);
});

jsFiddle 的jsfiddle

another workaround: 另一种解决方法:

var myarray = [];
$("#test").click(function() {
    myarray[index]=$("#drop").val();
    alert(myarray);
});

i wanted to add all checked checkbox to array. 我想将所有选中的复选框添加到数组中。 so example, if .each is used: 例如,如果使用.each:

var vpp = [];
var incr=0;
$('.prsn').each(function(idx) {
   if (this.checked) {
       var p=$('.pp').eq(idx).val();
       vpp[incr]=(p);
       incr++;
   }
});
//do what ever with vpp array;
var array = [];
var element = "anything you want in the array";
array.push(element); // array = [ "anything you want in the array" ]

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

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