gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:29:58 26 4
gpt4 key购买 nike

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

$(".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/

关于javascript - 如何创建包含自定义变量的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33465887/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com