Javascript对象属性不返回正确的长度

时间:2016-07-29 03:19:38

标签: javascript jquery object properties

我使用jQuery动态克隆元素并要求对象返回其长度,但每次都返回1。请看小提琴:

https://jsfiddle.net/gatzkerob/x5xd2x7q/3/

<span class="count">0</span>
<br>
<button>click</button>
<br>
<span class="a">a</span>

var obj = {
elem : $('.a')
}

function cloneThisAndCount(){
$('.a').last().after($('.a').first().clone());
$('.count').text(obj.elem.length);
}

$('button').click(function(){
cloneThisAndCount();
});

1 个答案:

答案 0 :(得分:2)

var obj = {
  elem : $('.a')
}

将被计算一次并缓存到begenning中的obj.elem。这将是1

注意(thanx到nnnnn):当你有一个jQuery对象的引用时,其他代码可能会更新该对象以向其添加更多元素。

解决方案1:

您需要做的是,每次在计算长度之前重做选择器。

&#13;
&#13;
function cloneThisAndCount() {
  $('.a').last().after($('.a').first().clone());
  $('.count').text($('.a').length);
}

$('button').click(function() {
  cloneThisAndCount();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="count">0</span>
<br>
<button>click</button>
<br>
<span class="a">a</span>
&#13;
&#13;
&#13;

解决方案2

obj更改为:

var obj = {
  elem : function(){ return $('.a')}
}

然后检查长度,如:$('.count').text(obj.elem().length);

&#13;
&#13;
var obj = {
  elem: function() {
    return $('.a')
  }
}

function cloneThisAndCount() {
  $('.a').last().after($('.a').first().clone());
  $('.count').text(obj.elem().length);
}

$('button').click(function() {
  cloneThisAndCount();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="count">0</span>
<br>
<button>click</button>
<br>
<span class="a">a</span>
&#13;
&#13;
&#13;