2010-12-17 48 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