【问题标题】:How to create a function containing custom var如何创建包含自定义 var 的函数
【发布时间】:2016-02-01 15:27:12
【问题描述】:

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

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

我知道有办法,但我不知道如何实现。如果有人能够帮助我,我非常感谢!

【问题讨论】:

  • 您在寻找这样的东西吗? jsfiddle.net/kishoresahas/49fn1jhk
  • 仅供参考,$($(this)[0]).val();$(this).val(); 相同,您可能只使用 this.value
  • 与往常一样,确定什么是固定的,什么是可变的(选择器和事件名称)。然后创建一个包含固定部分作为主体的函数(用可变部分替换,等待它,variables)并接受可变部分作为参数。

标签: javascript jquery function jquery-selectors jquery-events


【解决方案1】:

你可以写一个普通的函数,用合适的参数调用函数。

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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 2021-06-14
    • 2017-04-20
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多