【发布时间】:2013-10-25 15:45:40
【问题描述】:
[jsFiddle][1]
我需要使用 jQuery 按需访问正确的(显示的)[knob][2] 值。
我知道'change' 函数,但我需要同时访问多个旋钮的值。
我需要将每个旋钮的值乘以特定数量,然后将结果相加;有没有办法让'change' 函数提供旋钮的id 或其他标识属性,以便我的脚本可以区分它们的值?
这个计算功能是我目前所拥有的,我已经让它在每个旋钮的'change' 和点击按钮时触发:
function calculate() {
var result = 0;
$('.dial').each(function (e) {
result += $(this).val(); //Multiply by 1 to get an int
});
$('#result').text((typeof result) + ' ' + result); //Why is this a string in the first place?
}
用这个来设置旋钮:
$('.dial').each(function (e) {
$(this).knob({
max: 99,
width: 120,
height: 120,
bgColor: '#85d4b0',
fgColor: '#0ca961',
inputColor: '#0ca961',
thickness: 0.15,
change: function (v) {
console.log(v, this.v, this.cv);
calculate(); //I need it to (re-)calculate every time any knob's value changes
}
});
}
.val() 不起作用,因为它似乎落后了;第一次运行时,它不会更新结果和连续执行的次数,但会将其更改为之前的值。
有什么想法吗?
编辑:
如果我能得到值改变的旋钮的id,我可以执行以下操作:
var knobs = [{
id: '',
val: 0
}];
$('.dial').each(function () {
$(this).knob({change: function(v, id){
knobsMod(v, id);
}});
});
$('.dial').parent().each(function (e) {
$(this).attr('id', 'knob'+e);
if (e > (knobs.length - 1)) {
knobs[e] = $.extend({}, knobs[0]);
}
knobs[e].id = $(this).attr('id');
knobs[e].val = $(this).val()*1;
});
function knobsMod(v, id){
for (var i = 0; i < knobs.length; i++){
if (knobs[i].id === id){
knobs[i].val = v;
break;
}
}
}
然后它可以在重新计算时读取knobs 对象。
[1]:http://jsfiddle.net/SoullessWaffle/2mt2U/
[2]:http://anthonyterrien.com/knob/
【问题讨论】:
标签: javascript jquery jquery-events multiple-instances jquery-knob