使用数据属性通过 jquery 定位和更新变量

Using Data Attributes to Target and Update Variables With Jquery

本文关键字:定位 更新 变量 jquery 数据属性      更新时间:2023-09-26

我想知道如何使用数据属性来定位和更新变量。

链接到 JSFiddle

目录

<label>Update Foo</label>
<input type="range" class="slider"  min="1" max="100" step="1" value="50" data-var="foo">
<label>Update Bar</label>
<input type="range" class="slider"  min="1" max="100" step="1" value="10" data-var="bar">

JavaScript

var foo = 50, // when slider is changed these variables are updated
        bar = 10;
// update global variable
function updateVariable(variable, value) {
  variable = value;
  console.log(foo);
  console.log(bar);
  // other function called here that uses foo and bar
}
// input even listener
$('.slider').on("change mousemove", function() {
    updateVariable($(this).data("var"), $(this).val());
});

我想知道如何做到这一点的原因是因为我试图找出一种方法来拥有多个将更新变量的输入元素,同时保持 JS 简单。 这就是为什么事件不只是设置foo = $(this).val() 在我为每个输入元素制作事件侦听器和函数之前 - 所以,我想知道一种更有效的处理方法

为此,

您需要将三件事传递给updateVariable()方法:要更新的元素、要更新的 data-* 属性的名称以及要设置的值。像这样:

// update global variable
function updateVariable(el, dataAttr, value) {  
    $(el).data(dataAttr, value);
}
// input even listener
$('.slider').on("change mousemove", function() {
    updateVariable(this, 'var', this.value);
});

工作示例

话虽如此,我认为这种提取是完全多余的。您所做的只是包装jQuery自己的data()方法,并且不添加额外的业务逻辑或功能。您也可以从每个事件处理程序中调用data()

使用的方法将无法正常工作。它基本上是说$(this).data("var") = $(this).val()而不是更新变量 - 这是目标。 为了解决这个问题,我将foobar属性作为对象。

var myObject = {
    foo: 50,
    bar: 10
};
// input even listener
$('.slider').on("input", function() { //remove mouseover event to hide spam
    myObject[$(this).data("var")] = $(this).val();
    console.log("Foo: " + myObject.foo + " Bar: " + myObject.bar);
});
// Alternatively you can access properties objects like this  myObject["foo"] as well.

工作示例

这允许轻松访问这些属性,并允许以更简单的方式更新它们。