Javascript 事件驱动函数调用的jQuery逗号分隔选择器与变量
很抱歉问了这么长的问题。我有如下代码:Javascript 事件驱动函数调用的jQuery逗号分隔选择器与变量,javascript,jquery,jquery-ui,refactoring,Javascript,Jquery,Jquery Ui,Refactoring,很抱歉问了这么长的问题。我有如下代码: $("#el1, #el2, #el3, #el4, #el5").on("spinstop", function (event, ui) { updtpg() }); el1、el2等都是。然而,页面上大约有五个以上的按钮,但有些有时隐藏在其他按钮、下拉列表和复选框中。我将每一个连接到函数updtpg,该函数从微调器获取值并进行一些计算,更新results div 我将每个微调器的jQuery对象存储在全局对象中,如下所示: var win
$("#el1, #el2, #el3, #el4, #el5").on("spinstop", function (event, ui) {
updtpg()
});
el1、el2等都是。然而,页面上大约有五个以上的按钮,但有些有时隐藏在其他按钮、下拉列表和复选框中。我将每一个连接到函数updtpg,该函数从微调器获取值并进行一些计算,更新results div
我将每个微调器的jQuery对象存储在全局对象中,如下所示:
var window.gQ = {};
gQ.$el1 = $("#el1");
gQ.$el2 = $("#el2");
。。。并在updtpg函数中使用这些函数来获取微调器的值。我想做的是使用这个全局gQ对象中的属性来保存这些微调器的值。但是,这意味着要像这样连接每个微调器:
gQ.$el1.on("spinstop", function (event, ui) {
gQ.$val1 = gQ.$el1.val();
updtpg();
});
gQ.$el2.on("spinstop", function (event, ui) {
gQ.$val2 = gQ.$el2.val();
updtpg();
});
…每一个纺纱机都是如此。如果有道理的话,我不介意这样做。我想这是我的问题。这是正确的方法吗。我这样认为是因为我不希望每次微调器中的一个发生变化时都必须读取每个微调器的val函数,但它也会添加大量代码。相当重复的代码,引导。如果有更好的方法,我无法想象没有,那是什么
请随意更正您看到的任何其他看起来。。。嗯,可以改进。提前感谢。经验法则是,无论何时复制代码,都有更好的方法,下面是一个示例。首先创建主数组,为所有微调器创建事件处理程序。在每个事件中,我们将使用新值创建或更新数组,并调用您的函数。这将基于微调器id创建一个键值对
// Create the main array
var gQ = {};
$( "#spinner1, #spinner2, #spinner3" ).on("spinstop",function (event, ui) {
gQ[$(this).attr("id")] = $(this).val();
updtpg();
});
另一个技巧是在每个微调器上使用一个类,这样就不必指定所有ID,而只需指定一个类
<input id="spinner1" class="specialspinner" name="spinner" value="5.06" />
<input id="spinner2" class="specialspinner" name="spinner" value="5.06" />
<input id="spinner3" class="specialspinner" name="spinner" value="5.06" />
$( ".specialspinner" ).on("spinstop",function (event, ui) {
gQ[$(this).attr("id")] = $(this).val();
updtpg();
});
HTML
JSFIDLE示例:是否可以创建演示?根据我现在的理解,您想在微调器上使用一些类,如果它们是动态的$'body',则像这样选择它们。'spinstop','.spinner',functionevent,ui{//code goes here};,您还可以使用$this.data'spinValue',somevalue;
<input class="spinner" id="spinnerOne" type="text" />
<input class="spinner" id="spinnerTwo" type="text" />
<input class="spinner" id="spinnerTree" type="text" />
<div id="values"></div>
// values of spinner
var spinnerValues = {};
$('.spinner').each(function() {
// save jquery object
var $this = $(this);
// get id of spinner for saving values reference
var spinnerId = $this.attr('id');
// init values object
spinnerValues[spinnerId] = $this.val();
// attach event callback
$this.on('change', function (event, ui) {
// update values
spinnerValues[spinnerId] = $this.val();
// debug output - remove later!
console.log(spinnerValues);
});
});