我正在使用 jQuery,这是我用于任何标签的点击事件的代码。
$('.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);
};
我的新 block 代码应该是这样的:
$('.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(this);
然后像这样定义函数:
function getValues(element){
unitPrice = parseFloat($(element).closest('.product').find('.unit-price span').text().substring(3));
subTotal = parseFloat(inputValue * unitPrice).toFixed(2);
return subTotal;
$(element).closest('.product').find('.total-price span').text(subTotal);
};
关于javascript - 在 javascript 函数中使用选择器 "$(this).find()"jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36629193/