2013-01-09 37 views
0

你好我试图找到一种方法,通过一些动态生成的options.I循环已经tryed做这样的:循环throught动态地生成选项

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也看不到任何的生成items.I使用jquery 1.5.1。

我该如何解决这个问题?

编辑

到目前为止,我在管理,选择到目前为止,我可以告诉大家,既不设法看到是dynamilt created.It的DOM元素我已经tryed生成的elements.From方法没有运气如果他们不在那里,但如果我用Firebug检查,我可以看到他们。这个问题出现beucase我正在创建一个Ajax调用之后呢?

回答

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); 
    } 
}); 
+0

这似乎并没有工作,我已经tryed几种方法,我发现在互联网上的,似乎所有的方法jquery没有看到选择选项,但如果我检查他们在那里的dom .Ca这是因为我在ajax调用后创建它们? –

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; 
     } 
    }