如何创建包含自定义变量的函数

How to create a function containing custom var

本文关键字:自定义 变量 函数 包含 何创建 创建      更新时间:2023-09-26

我已经编写了以下函数来同步一些输入字段:

$(".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');

我知道有办法,但我不知道如何做到这一点。如果有人能帮助我,我非常感谢!

您可以编写一个通用函数,并使用适当的参数调用该函数。

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/1/