2014-03-28 31 views
0

我试图完全脚本这个复选框检查/取消选中代码片段在jQuery中,但它没有任何成功。这里是jQuery的/ JavaScript代码:更优雅的方式(un)在jQuery中检查?

$.ajax({ 
       type: "GET", 
       url: "check.xml", 
       cache: false, 
       dataType: "xml", 
       success: function(xml) { 
        $(xml).find("check").each(function(){ 
         $(xml).find("todo").each(function(){ 
          var state = $(this).attr("state"); 
          if (state == "true") { 
           document.getElementById($(this).attr("id")).checked = true; 
          } else { 
           document.getElementById($(this).attr("id")).checked = false; 
          } 
         }); 
        }); 
       } 
      }); 

这也可能是非常有可能只使用jQuery的做document.getElementbyId(blablabla)....。我尝试这样做:

($(this).attr("id")).prop("checked", true)

但是,这并没有真正按预期工作。有什么建议么?

+0

http://stackoverflow.com/questions/426258/how-do- i-check-a-checkbox-with-jquery – MSadura

+0

我试过了,但是按照评论,它没有工作。 – maikovich

回答

0

你错过了在选择了“#”:

var id = '#'+ $(this).attr("id"); 

然后你就可以做一个衬垫,而不是 “如果”:

$(id).prop("checked", (state == "true")); 
+0

这就是我的意思是优雅。谢谢。 – maikovich

1

你需要做的是这样的(注意#符号来从ID的要素 - 而不是CSS选择器相同的规则) -

var id = $(this).attr("id"); 
$('#'+ id).prop("checked", true); 
+1

是不是只是'$(this).prop('checked',true)'? –

+2

@ D.Kasipovic不,Op正在遍历xml,而不是实际的DOM元素 –

+0

哦,对,注意那里。 –