在其 click() 函数中是否有更简洁/更简单的方法来获取复选框元素的“catNum”值?
function createCategoriesList() {
var catNames = new Array("First cat", "Second cat", "Third cat");
var catImageURLs = new Array("First.png", "Second.png", "Third.png");
jQuery('<ul/>', {
id: 'map-cats'
}).appendTo('#map-controls');
for(var i = 0; i < catNames.length; i++ ) {
var listItem = jQuery('<li/>').appendTo('#map-cats');
jQuery('<img/>', {
src: catImageURLs[i],
alt: ''
}).appendTo(listItem);
var checkbox = jQuery('<input/>', {
type: 'checkbox',
checked: 'checked',
id: 'cat_' + i,
name: 'cat_' + i
}).appendTo(listItem);
checkbox.data("catNum", i);
checkbox.click(function() {
//alert("The cat num selected is: " + this.data("catNum")); //throws exception
alert("The cat num selected is: " + jQuery('#' + this.id).data('catNum')); //works but there must be a better way??
});
jQuery('<label/>', {
htmlFor: catImageURLs[i],
text: catNames[i],
for: 'cat_' + i
}).appendTo(listItem);
}
}