javascript - 在 javascript 函数中使用选择器 "$(this).find()"jQuery

标签 javascript jquery html

我正在使用 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);
};

参见 How does the "this" keyword work?

关于javascript - 在 javascript 函数中使用选择器 "$(this).find()"jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36629193/

相关文章:

JavaScript 分割错误 : Uncaught TypeError: Cannot read property 'split' of undefined

javascript - perl cgi 脚本无法发布到站点 - 独立工作但在 apache 下运行时失败

jquery - 如何正确打破 promise 链?

javascript - 无法在 node.js 中加载 js 和 css 文件

javascript - HTML 和 JavaScript 自动递增数字

javascript - 下拉框截掉一个值?

javascript - 窗口关闭时的 Ember 事件

javascript - jquery删除文件夹中的图像文件而不使用php或ajax

javascript - mongodb 服务器端 javascript 实际上是客户端?

javascript - 的下一个实例