jQuery函数与事件的公共因子

jQuery common factor of functions with events

本文关键字:函数 事件 jQuery      更新时间:2023-09-26

我有这样的代码:

$(document).ready( function(){
    var gold;
    var silver;
    var copper;
    $("#gold").change(function(){
        gold = $(this).val();
    });
    $("#silver").change(function(){
        silver = $(this).val();
    });
    $("#copper").change(function(){
        copper = $(this).val();
    });
});

只要文本字段发生变化,它就会更新变量,这就是html:

<input type="text" id="gold">
<input type="text" id="silver">
<input type="text" id="copper">

如果我必须申报类似的东西:

$("#copper").change(function(){
    copper = $(this).val();
}); 

对于我得到的每一个变量,当我有100多个变量时,我能做什么?我想避免在他们的事件中得到元素1比1。。。

我试过这样的东西:

var gold = dynamicValue("gold");
function dynamicValue(element){
    $("#" + element).change(function(){
        return $(this).val();
    });
}

但似乎不起作用。。。

如果你的结构总是这样,我建议你这样做。

var values = {};
$('input').change(function(){
   values[this.id] = this.value;
});

像这样,它将创建一个以ID为键、以输入值为键值的对象。

values = {
   gold: 'something',
   copper: 'something',
   silver: 'comething'
}

你将能够在任何时候得到它们

var gold = values.gold;

如果得到undefined,则意味着输入尚未更改。下的示例

var values = {};
$('input').change(function() {
  values[this.id] = this.value;
  $('div').text(JSON.stringify(values)); // this line is only for the example
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="gold">
<input type="text" id="silver">
<input type="text" id="copper">
<input type="text" id="gold1">
<input type="text" id="silver2">
<input type="text" id="copper4">
<div></div>

HTML

<input type="text" class="metal-input" id="gold">
<input type="text" class="metal-input" id="silver">
<input type="text" class="metal-input" id="copper">

jQuery

var metals = {};
$('.metal-input').on('input', function() {
    metals[this.id] = $(this).val();
    console.log(metals);
});

使用类并将id用作密钥

$(document).ready( function(){
  var metals = 
      { gold : null, silver : null, copper : null}
  $(".inputs").change(function(){
    metals[this.id] = $(this).val();
    console.log(metals);
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="gold">gold</label><input type="text" id="gold" class="inputs">
<label for="silver">silver</label><input type="text" id="silver" class="inputs">
<label for="copper">copper</label><input type="text" id="copper" class="inputs">