[英]jQuery common factor of functions with events
I've got this code: 我有以下代码:
$(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();
});
});
It just updates the variable whenever the textfield changes, this is the html: 只要文本字段更改,它就更新变量,这就是html:
<input type="text" id="gold">
<input type="text" id="silver">
<input type="text" id="copper">
If i had to declare something like: 如果我必须声明:
$("#copper").change(function(){
copper = $(this).val();
});
for every variable ive got, what can i do when i have over 100 variables? 对于每个得到的变量ive,当我拥有超过100个变量时该怎么办? I want to avoid getting elements 1 by 1 with theyr events...
我想避免在theyr事件中一一获取元素...
I have tried something like this: 我已经尝试过这样的事情:
var gold = dynamicValue("gold");
function dynamicValue(element){
$("#" + element).change(function(){
return $(this).val();
});
}
But doesn't seem to work... 但是似乎不起作用...
If you're structure is always like that I would recommend something like this. 如果您的结构总是这样,那么我会推荐这样的东西。
var values = {};
$('input').change(function(){
values[this.id] = this.value;
});
Like this it will create an object with the IDs as keys and in input values as the key value. 这样,它将创建一个ID为键,输入值为键值的对象。
values = {
gold: 'something',
copper: 'something',
silver: 'comething'
}
and you will be able to get them anytime 您将可以随时获取它们
var gold = values.gold;
If you get undefined
it will mean that the input has not yet been changed. 如果
undefined
,则表示输入尚未更改。 Example below 下面的例子
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 的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 jQuery的
var metals = {};
$('.metal-input').on('input', function() {
metals[this.id] = $(this).val();
console.log(metals);
});
Use a class and use the id as a key 使用一个类并使用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">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.