我正在使用jQuery,这是我用于任何标签的click事件的代码。
$('.spin span:last-child').click(function(){
unitPrice = parseFloat($(this).closest('.product').find('.unit-price span').text().substring(3));
if ( $(this).parent().find($('.custom-input')).val() == "" ) {
$(this).parent().find($('.custom-input')).val(1);
inputValue = parseInt($(this).parent().find($('.custom-input')).val());
subTotal = parseFloat(inputValue * unitPrice).toFixed(2);
$(this).closest('.product').find('.total-price span').text(subTotal);
} else if ( inputValue =! "" ) {
inputValue = parseInt($(this).parent().find($('.custom-input')).val());
inputValue += 1
$(this).parent().find($('.custom-input')).val(inputValue);
subTotal = parseFloat(inputValue * unitPrice).toFixed(2);
$(this).closest('.product').find('.total-price span').text(subTotal);
};
});
因此,我创建了一个函数来优化代码:
function getValues(){
unitPrice = parseFloat($(this).closest('.product').find('.unit-price span').text().substring(3));
subTotal = parseFloat(inputValue * unitPrice).toFixed(2);
return subTotal;
$(this).closest('.product').find('.total-price span').text(subTotal);
};
我的新块代码应如下所示:
$('.spin span:last-child').click(function(){
if ( $(this).parent().find($('.custom-input')).val() == "" ) {
$(this).parent().find($('.custom-input')).val(1);
inputValue = parseInt($(this).parent().find($('.custom-input')).val());
getValues();
} else if ( inputValue =! "" ) {
inputValue = parseInt($(this).parent().find($('.custom-input')).val());
inputValue += 1
$(this).parent().find($('.custom-input')).val(inputValue);
getValues();
};
});
但是我的函数“ getValues”不起作用,函数内部的选择器“ $(this).find ...”应该是我认为的问题,你们可以帮忙解决此问题吗?
谢谢
我建议不要更改函数定义,以允许将您正在使用的元素传递给它,而不用担心在this
内部getValues
进行构造。
您的函数中还存在一些错误:return
如果该函数执行,则ing将结束执行,因此后一行return
当前将不运行,您应该始终使用var
来声明变量。您没有使用此函数的结果,因此您实际上根本不需要该return
语句。
function getValues(spanEl) {
var unitPrice = parseFloat($(spanEl).closest('.product').find('.unit-price span').text().substring(3));
var subTotal = parseFloat(inputValue * unitPrice).toFixed(2);
$(spanEl).closest('.product').find('.total-price span').text(subTotal);
};
然后随便打电话getValues()
到getValues(this);
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句