如何将元素添加到jquery数组?

时间:2017-10-27 23:34:37

标签: jquery

https://codepen.io/anon/pen/pdobWy

都返回0

我想要什么?

它返回1.

我可以使用

x.each(function(i, el){...});

用它编码

https://codepen.io/anon/pen/pdobWy

$(function($){
  var x = $([]);
  x.add('biippo');
  console.error(x.length); // returns 0

  x[0] = 'foo';
  console.error(x.length); // returns 0
});

2 个答案:

答案 0 :(得分:1)

您需要使用“推送”而不是“添加”。

试试这个x.push('biippo');代替x.add('biippo');

Please check the updated fiddle.

$(function($){
  var x = $([]);
  x.push('biippo');
  console.error(x.length);
  
  x[0] = 'foo';
  console.error(x.length);
  
  $.each(x, function(index, element){ console.log(element); });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:1)

也许这个序列会有所帮助:

var arr = ['a', 'b', 'c'];

var x = $(arr); // form a jQuery collection
console.log(x.length); // 3

arr.push('d'); // push 'd' onto the original array
console.log(x.length); // still 3 (x is not a 'live' representation of arr)

x = x.add('d'); // select DOM element with tagName 'd'
console.log(x.length); // still 3 (no DOM element was selected)

x.add($(['d'])); // merge a new jQuery collection with x
console.log(x.length); // still 3 (.add() returns a new jQuery selection containing 4 elements, but leaves x unchanged)

x = x.add($(['d'])); // merge a new jQuery collection with x, and assign to x
console.log(x.length); // 4 (.add() returns a new jQuery selection containing 4 elements, and x is changed by assignment).

<强> demo