Javascript Jquery array.push() 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8413523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery array.push() not working
提问by Saad Bashir
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. Following is the jsFiddle link: http://jsfiddle.net/dKWnb/3/
我一直在尝试使用 Jquery array.push() 函数将下拉列表中的变量添加到数组中,但由于某些奇怪的原因它不起作用。以下是 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>
回答by Manse
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);
});
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()方法。
回答by Interrobang
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);
});
回答by sifr_dot_in
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;