使用数据属性通过 jquery 定位和更新变量
Using Data Attributes to Target and Update Variables With Jquery
我想知道如何使用数据属性来定位和更新变量。
链接到 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()
而不是更新变量 - 这是目标。 为了解决这个问题,我将foo
和bar
属性作为对象。
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.
工作示例
这允许轻松访问这些属性,并允许以更简单的方式更新它们。
相关文章:
- CSS-如何定位内容数据标题
- Javascript循环不会自我更新
- 添加文字和评论功能更新Div
- Jquery菜单操作不稳定,定位不正确,存在一般错误
- 在Jquery detachment()和appendTo()之后定位元素
- 困在逻辑中试图定位动态的东西
- AngularJS:ng之后,重复$scope值未按预期更新
- 如何通过数组更新角度子范围
- Ajax聊天消息重复而不仅仅是更新
- 通过CSV文件上载更新数据库表
- 平均值:无法将数据更新到数据库
- $rootScope未使用forEach进行更新
- d3基于用户选择动态更新节点
- 有条件更新d3.js力图中节点的最佳方法
- Angular:更新一次性绑定的数据
- .scroll()函数在上次更新后在谷歌chrome中定位闪烁
- Chrome地理定位在更新后停止工作
- 使用数据属性通过 jquery 定位和更新变量
- Safari:绝对定位的DIV在通过DOM更新时不会移动
- Ionic / Angular JS -使用地理定位后输入字段不能正确更新