1

我寫了下面的功能同步一些輸入字段的功能:如何創建一個包含自定義變量

$(".dp1").on('change', function(e){ 
    var dateValue = $($(this)[0]).val(); 
    $.each($('.dp1'), function(index, item){ 
     $(item).val(dateValue); 
    }); 
}); 

$(".dp2").on('change', function(e){ 
    var dateValue = $($(this)[0]).val(); 
    $.each($('.dp2'), function(index, item){ 
     $(item).val(dateValue); 
    }); 
}); 

$(".rooms").on('keyup', function(e){ 
    var dateValue = $($(this)[0]).val(); 
    $.each($('.rooms'), function(index, item){ 
     $(item).val(dateValue); 
    }); 
}); 

$(".persons").on('keyup', function(e){ 
    var dateValue = $($(this)[0]).val(); 
    $.each($('.persons'), function(index, item){ 
     $(item).val(dateValue); 
    }); 
}); 

由於功能是完全相同的一個,每次,我想有一個更好的方式來結合它合併成一個。我在想像

my_custom_function(my_custom_value){ 
    var dateValue = $($(this)[0]).val(); 
    $.each($('my_custom_value'), function(index, item){ 
     $(item).val(dateValue); 
    }); 
} 
my_custom_function('.dp1, .dp2, .rooms, .persons'); 

我知道有一種方法,但我不知道如何實現這一點。我非常感謝能夠幫助我的人!

+0

你在尋找這樣一些事情? http://jsfiddle.net/kishoresahas/49fn1jhk/ –

+0

也試試這個http://jsfiddle.net/kishoresahas/49fn1jhk/1/ –

+1

FYI,'$($(this)[0])。val() ;'和$(this).val();'相同,你可以使用'this.value'。 –

回答

2

您可以編寫一個通用函數並使用approprite參數調用該函數。

function my_custom_function(selector, event) { 
 
    $(selector).on(event, function (e) { 
 
     var dateValue = this.value; 
 
     $.each($(selector), function (index, item) { 
 
      $(item).val(dateValue); 
 
      console.log(item); 
 
     }); 
 
    }); 
 
} 
 

 
my_custom_function(".dp1", "change") 
 

 
my_custom_function(".dp2", "change") 
 

 
my_custom_function(".rooms", "keyup") 
 

 
my_custom_function(".persons", "keyup")
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" class="dp1"></input> 
 
<input type="text" class="dp1"></input> 
 
<br/> 
 
<input type="text" class="dp2"></input> 
 
<input type="text" class="dp2"></input> 
 
<br/> 
 
<input type="text" class="rooms"></input> 
 
<input type="text" class="rooms"></input> 
 
<br/> 
 
<input type="text" class="persons"></input> 
 
<input type="text" class="persons"></input>

DEMO:http://jsfiddle.net/kishoresahas/49fn1jhk/1/

相關問題