您好我正在尝试找到一种方法来循环一些动态生成的选项。我试着这样做:
console.log($("select#subcategory option").length);
$("select#subcategory option").each(function () {
console.log($(this).val() + "ceva");
if ($(this).val() == subcategoryId) {
console.log($(this).val());
$(this).attr("selected", "selected");
}
});
看来似乎jquery没有看到任何生成的项目。我正在使用jquery 1.5.1。
我该如何解决这个问题?
修改
到目前为止,我没有运气选择生成的元素。从我到目前为止尝试的方法我可以看出,它们都没有设法看到动态创建的dom元素。就像它们不存在一样,但是,如果我查看Firebug,我可以看到它们。可以看到这个问题beucase我在ajax调用后创建它们吗?
答案 0 :(得分:1)
你可以使用普通的香草javascript:
var select = document.getElementById('subcategory');
for (var i=0; i<select.options.length; i++) {
console.log(select.options[i]);
if (select.options[i].value==subcategoryId) {
select.selectedIndex = i;
break;
}
}
答案 1 :(得分:1)
试试这个:
$(document).find("select#subcategory option").each(function () {
var subcategoryId = $('#subcategory').attr('id');
console.log($(this).val() + "ceva");
if ($(this).val() == subcategoryId) {
console.log($(this).val());
$(this).prop("selected", true);
}
});