我有一个 Ajax 请求,它返回了一个格式如下的 JSON 数组:[101, 102]数组中的数据是存储在数据库中的图像的 ID。
我想做的是显示页面上的所有图像,并在每个单独的图像旁边添加一个复选框。如果image_id在上面的数组中,那么我希望选中该复选框。
除了选中复选框外,一切都正常工作
这是我的代码片段:
$.get('get_thumbs.php?category=' + selected,
function (data) {
$.get('get_selected_photos.php?product_id=' + product,
function (returned) {
po = $.parseJSON(returned);
});
var d = $.parseJSON(data);
if (d != null) {
var fieldWrapper = $("<ul>");
$.each(d, function (index, value) {
var checked = "";
var fName = $("<li><img src="../" + value["thumb"] + ""</li>");
var fType = $('<input>', {
type: "checkbox",
id: "checkbox" + value["photo_id"],
value: value["photo_id"],
checked: ($.inArray(value["photo_id"], po) > 0 ? true : false)
});
fType.click(function () {
var intId = $(this).val();
if ($(this).is(':checked')) {
var sel = $(this).val();
$.get('get_sizes.php?photo_id=' + sel,
function (data) {
var d = $.parseJSON(data);
var tableWrapper = $("<div class="fieldwrapper" id="field" + intId + ""/>");
var tName = d;
tableWrapper.append(tName);
$("#buildyourform").append(tableWrapper);
});
} else {
$("#field" + intId).slideUp(function () {
$(this).remove();
})
}
$("#buildyourform").show();
});
fType.unbind("click", function () {
$(this).parent().remove()
});
fName.append(fType);
fieldWrapper.append(fName);
});
$("#avail_images").append(fieldWrapper);
} else {
$("#avail_images").html("<h2>There are currently no images associated with this Category.</h2>");
}
问题是($.inArray( value["photo_id"], po ) > 0 ? true : false)
似乎无法正常工作。变量"po"是从 AJAX 调用填充的,所以也许我错过了一些东西。
任何建议都非常感谢。
我建议您在代码中加入 Underscore.js,它会改进很多,它会让你的生活 easier.is 非常容易阅读,它具有跨浏览器支持。
http://underscorejs.org/
真的很啰嗦。
_.isArray(someVariable); // boolean return
它还提供了许多用于操作数据的功能。例子:
_.isEmpty([]); // validates empty string, empty arrays, and empty objects {}
_.last([1, 2, 3, 4, 39]); // returns the last item on array
看一看
干杯