如何创建一个包含自定义变量
问题描述:
我写了下面的功能同步一些输入字段的功能:如何创建一个包含自定义变量
$(".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');
我知道有一种方法,但我不知道如何实现这一点。我非常感谢能够帮助我的人!
答
您可以编写一个通用函数并使用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>
你在寻找这样一些事情? http://jsfiddle.net/kishoresahas/49fn1jhk/ –
也试试这个http://jsfiddle.net/kishoresahas/49fn1jhk/1/ –
FYI,'$($(this)[0])。val() ;'和$(this).val();'相同,你可以使用'this.value'。 –