[英]jQuery common factor of functions with events
我有以下代碼:
$(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();
});
對於每個得到的變量ive,當我擁有超過100個變量時該怎么辦? 我想避免在theyr事件中一一獲取元素...
我已經嘗試過這樣的事情:
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">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.