繁体   English   中英

jQuery具有事件功能的共同因素

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM