簡體   English   中英

如何將相同的$(document).ready(function()用於多個輸入?

[英]How can I use the same $(document).ready(function() for multiple inputs?

我是JavaScript / jQuery的新手,使用DatePicker在表單中有4個日期選擇。

看到設置相同,我嘗試對所有4個日期選擇都使用dp1,但是它不起作用。 第一個日期選擇有效,而其他三個則無效。

因此,目前我正在這樣做,但是由於設置相同,似乎沒有意義的額外代碼。

<script type='text/javascript'>
  $(document).ready(function() {
     $('#dp1').datepicker({
         autoclose: true,
         format: "yyyy-mm-dd"
     });
  });
</script>

<script type='text/javascript'>
  $(document).ready(function() {
     $('#dp2').datepicker({
         autoclose: true,
         format: "yyyy-mm-dd"
     });
  });
</script>

<script type='text/javascript'>
  $(document).ready(function() {
     $('#dp3').datepicker({
         autoclose: true,
         format: "yyyy-mm-dd"
     });
  });
</script>

<script type='text/javascript'>
  $(document).ready(function() {
     $('#dp4').datepicker({
         autoclose: true,
         format: "yyyy-mm-dd"
     });
  });
</script>

還有另一種方法嗎?

當然可以:)並且請注意,您甚至不需要使用4個不同的datepicker函數,因為您可以使用jQuery選擇器將所有4個datepicker定位為這樣:

<script type='text/javascript'>
 $(document).ready(function() {

    $('#dp1, #dp2, #dp3, #dp4').datepicker({

     autoclose: true,
     format: "yyyy-mm-dd"

     });

  });
 </script>

是! 你可以這樣做:

<script type='text/javascript'>
  $(document).ready(function() {
     $('#dp1').datepicker({
         autoclose: true,
         format: "yyyy-mm-dd"
     });
     $('#dp2').datepicker({
         autoclose: true,
         format: "yyyy-mm-dd"
     });
     $('#dp3').datepicker({
         autoclose: true,
         format: "yyyy-mm-dd"
     });
     $('#dp4').datepicker({
         autoclose: true,
         format: "yyyy-mm-dd"
     });
  });
</script>

或者(只給他們所有一個CSS類all_dps

<script type='text/javascript'>
$(document).ready(function() {

  $('.all_dps').datepicker({
   autoclose: true,
   format: "yyyy-mm-dd"
  });

});
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM