【发布时间】:2014-03-19 17:52:41
【问题描述】:
你可以在这里看到jsfiddle.net/TTU4Z/1/ 有问题的 jquery 代码在下面,如果我在没有我所有代码的情况下运行它(如在 jsfiddle 中),它运行完美。但是我的所有代码都没有运行。
$(document).ready(function() {
// This button will increment the value
$('.plus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[id='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[id='+fieldName+']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[id='+fieldName+']').val(0);
}
});
// This button will decrement the value till 1
$(".minus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[id='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[id='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[id='+fieldName+']').val(0);
}
});
});
单击“添加”按钮一切都很好,但是当您单击减号或加号按钮之一时,它会全部删除。
如您所见,它应该增加或减少相对输入的 val,但如果我尝试编辑这些函数中的所有内容,则没有任何变化。 怎么办?
【问题讨论】:
-
那是很多重复的代码。您应该为两者使用一个函数,通过
data-*属性或hasClass()检查传递是否应该添加或减去。此外,field不是有效的 HTML 属性:您应该改用data-field。
标签: javascript jquery html css increment