我有这样的事情:
var menu = (function() {
var itemContainer = $('#item-container');
var items = $('.item');
return {
countItems: function() {
//do something with items object. This does not work.
console.log('items.length: ' + items.length)
},
manipulateItemContainer: function() {
//do something with itemContainer object. This works fine.
},
populate: function() {
//dynamically create elements with .item class
var item1 = $('<div/>', {
class: 'item'
}).appendTo(itemContainer);
var item2 = $('<div/>', {
class: 'item'
}).appendTo(itemContainer);
var item3 = $('<div/>', {
class: 'item'
}).appendTo(itemContainer);
},
addItem: function() {
var item = $('<div/>', {
class: 'item'
}).appendTo(itemContainer);
}
}
})();
menu.populate();
menu.countItems();
menu.addItem();
menu.countItems();
&#13;
.item {
width: 20px;
height: 20px;
display: inline-block;
background-color: green;
margin: 1px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item-container">
</div>
&#13;
在这种情况下,items
为空。我该如何重新配置以解决这个问题?创建init()
函数并在.populate()
结束时运行它?其他选择?或者我完全错过了其他的东西?
答案 0 :(得分:1)
由于可用的项目数是动态的,因此使用函数调用检索它们可能会更好:
var menu = function() {
var itemContainer = $('#item-container');
function getItems() {
return $('.item');
}
return {
manipulateItems: function() {
//do something with items object. This does not work.
// check if there are any items first
if (getItems()) {
// work with items
}
},
manipulateItemContainer: function() {
//do something with itemContainer object. This works fine.
},
populate: function() {
//dynamically create elements with .item class
}
}
}