2011-10-22 98 views
20

我有了一個日期輸入jQuery的多個ID相同的功能

<td style="background-color:#c6efce"><input type="text" id="datepicker0"></td> 
<td style="background-color:#c6efce"><input type="text" id="datepicker1"></td> 
<td style="background-color:#c6efce"><input type="text" id="datepicker2"></td> 
<td style="background-color:#c6efce"><input type="text" id="datepicker3"></td> 
<td style="background-color:#c6efce"><input type="text" id="datepicker4"></td> 

表我想通過訪問它的第一個

<script> 
    $(function() { 
     $("#datepicker0").datepicker({ 
      showButtonPanel: true 
     }); 
    }); 
    </script> 

如何訪問一切嗎?

回答

50

您可以使用「attribute starts-with」選擇:

$(function() { 
    $("input[id^='datepicker']").datepicker({ 
     showButtonPanel: true 
    }); 
}); 

那選擇將匹配任何input元素,它的id值與「日期選擇器」開始。另一種選擇是將所有必需的元素都提供給一個普通的類。

您可以通過id用逗號分隔的列表還可以選擇多個元素:

$("#datepicker0, #datepicker1, #datepicker2"); //List as many as necessary 

但是,這不是如果你需要添加更多的投入特別是可擴展性。

10

最好的辦法是使用一類:

<td style="background-color:#c6efce"><input type="text" class="dp" id="datepicker0"></td> 
<td style="background-color:#c6efce"><input type="text" class="dp" id="datepicker1"></td> 
<td style="background-color:#c6efce"><input type="text" class="dp" id="datepicker2"></td> 
<td style="background-color:#c6efce"><input type="text" class="dp" id="datepicker3"></td> 
<td style="background-color:#c6efce"><input type="text" class="dp" id="datepicker4"></td> 
<script> 
    $(function() { 
     $(".dp").each(function(){ 
      $(this).datepicker({ 
       showButtonPanel: true 
      }); 
     }) 
    }); 
</script> 

,但你也可以使用這個:

<td style="background-color:#c6efce"><input type="text" id="datepicker0"></td> 
<td style="background-color:#c6efce"><input type="text" id="datepicker1"></td> 
<td style="background-color:#c6efce"><input type="text" id="datepicker2"></td> 
<td style="background-color:#c6efce"><input type="text" id="datepicker3"></td> 
<td style="background-color:#c6efce"><input type="text" id="datepicker4"></td> 

<script> 
    $(function() { 
     $("#datepicker0,#datepicker1,#datepicker2,#datepicker3,#datepicker4").datepicker({ 
      showButtonPanel: true 
     }); 
    }); 
</script> 

第二種方法是不明智的。

+1

爲什麼您使用的每個函數在第一個例子,而不是像第二個節點列表上調用日期選擇器? – mikerobi

+0

@mikerobi哈哈好點XD也許你可以提交這樣的答案? –

+0

謝謝@JosephMarikle – sradha

0

而不是ID,你應該使用一個名爲類似於has-datepicker的CSS類並搜索它。

4

正如我理解你的問題,你試圖使用jQuery選擇多個ID。以下是你如何做到的:

$('#1,#2,#3') 

你只需用逗號分隔這些ID。

但是,這不是實現這一目標的最佳方法。你真的應該使用一個類:爲每一個td類及用途:

$('td.myClass') 

或者,您可以分配一個ID表,並選擇它的所有td孩子。 HTML:

<table id="myTable"> 
    <td>text</td> 
    <td>text</td> 
</table> 

的jQuery:

$('table#myTable td') 
0

jQuery UI的自動添加 「hasDatePicker」 類具有日期選擇器的所有元素。你可以查詢頁面的東西像$(「input.hasDatePicker」)來獲取所有日期選擇器。

+0

沒有'datepicker'應用於元素之前(在這種情況下...) –

+0

啊,我讀了原來的問題錯了,認爲原始問題詢問有關訪問它們,而不是創建它們,但我想OP確實提供了一個代碼片段,他表明他正在創建一個... – ima007

0

您可以使用此以及 $('#datepicker0,#datepicker1,#datepicker2,#datepicker3,#datepicker4)