2010-12-17 70 views
1

我的问题与我的jQuery代码在哪里我的Firebug给我警告:选择器的预期。jQuery Selector预计

下面是代码:

$("img[id$='_tick']").each(function() { 

    $(this).click(function() { 

     var tickIDFinder = $(this).attr("id"); 
     var tickSection = tickIDFinder.slice(0,1); 

     var checkboxID = "\"input[id^='" + tickSection + "_checkbox_']\""; 
     var airTableID = "#" + tickSection + "_airline_table tr"; 

     $(checkboxID).each(function() { 

      if ($(this).is('checked')) { 
       alert("Checkbox is Checked."); 
      } 

      $(this).attr('checked','checked'); 

     }); 

    }); 

}); 

我试图做的是写一个jQuery允许用户点击一个链接(如图像)。当用户点击这个图像时,它会'检查'指定的所有复选框。然后我会从Firebug获得Selector预期的警告。

jQuery本身正在按照我的预期工作。我只是想尝试解决警告。

任何人都可以帮忙吗?我真的很感激。

感谢您的想法堆。

回答

2

除了其他的答案,这可以进一步简化,像这样:

$("img[id$='_tick']").click(function() { 
    var tickSection = this.id.slice(0,1); 

    var checkboxID = "input[id^='" + tickSection + "_checkbox_']"; 
    var airTableID = "#" + tickSection + "_airline_table tr"; 

    $(checkboxID).each(function() { 
     if (this.checked) { 
      alert("Checkbox is Checked."); 
     } 
     $(this).attr('checked', true); 
    }); 
}); 

这里有几件事:

  • 你不需要.each(),只需.click(),它会绑定到他们所有的人。
  • 在可用时使用DOM属性,例如, this.idthis.checked
  • checkboxID有额外的引号的选择,删除它们

可能找不到调试,这是更简单,如.attr()作品上的多个元素,以及:

$("img[id$='_tick']").click(function() { 
    $("input[id^='" + this.id.slice(0,1) + "_checkbox_']").attr('checked', true); 
}); 
+0

我有几个参考,做.each()和.click()可能对我没有任何好处。谢谢你为我确认。 – Arief 2010-12-17 04:19:59

1

更换

if ($(this).is('checked')) 

if ($(this).is(':checked')) 

:checked

您可以使用this.id这将快于$(this).attr("id")

var tickIDFinder = this.id; 
+1

虽然这是正确的在他之后......不会导致他得到的错误,而$(this).is(':checked')'无论如何都应该是'this.checked'。 – 2010-12-17 03:17:25

4

更换

var checkboxID = "\"input[id^='" + tickSection + "_checkbox_']\""; 

var checkboxID = "input[id^='" + tickSection + "_checkbox_']"; 

(除了什么@rahul说:)

+0

谢谢你。一旦我改变了这个,并且:检查了,我再也没有收到警告。 – Arief 2010-12-17 03:17:18

+2

如果@ sje397的答案有效,那么将其标记为接受的答案。 – AniDev 2010-12-17 03:24:38