为什么在jquery处理程序中没有第二次调用单个函数?

时间:2017-06-08 16:50:48

标签: javascript jquery

我正在尝试创建两个div,它们在鼠标点击时响应,同时增加或减少饱和度。这是我的问题的一个简短的小提琴: https://jsfiddle.net/ds6w5uwj/

$(document).ready(function() {
  var oldbgc;
  oldbgc = void 0;
  return $(document.body).on('click', '.prio-step', function() {
    var bg, newbgc;
    alert("color recalc started");
    bg = $(this).css('background-color');
    oldbgc = rgb2hex(bg); //This line is only executed in the very first run
    newbgc = applySaturationToHexColor(oldbgc, 30);
    return $(this).css({
      backgroundColor: newbgc
    });
  });
});

第一次单击一个div时,将调用rgb2hex(bg)并将正确的值写入oldbgc。但是,当您尝试再次单击时,无论您想要哪个div,脚本都会跳过导致NaN错误的特定行。 我发现这两个函数applySaturationToHexColor(...)rgb2hex(...)是stackoverflow.com上相应问题的最佳答案。

1 个答案:

答案 0 :(得分:0)

在您的代码中,我看到了范围问题。

您的代码中的这些行中有一些内容。

rgb2hex= function(rgb_in) { <============= #1
    // removed for simplicity
};

applySaturationToHexColor= function(hex, saturationPercent) {
    // removed for simplicity
    rgb2hex = function(rgb) { <============= #2
      return '#' + floatToHex(rgb[0]) + floatToHex(rgb[1]) + floatToHex(rgb[2]);
    };
    newHex = rgb2hex(newRgbIntensityFloat); <============= #3
    return newHex;
};

$(document).ready(function() {
    // removed for simplicity
    $(document.body).on('click', '.prio-step', function() {
       oldbgc = rgb2hex(bg); <============= #4
    });
    // removed for simplicity
  });
});

仔细检查我指向1,2,3和4的线。你已经定义了rgb2hex两次,一次在指针#1处,第二次指向指针#2。因此,当您想要调用指针#1中定义的函数时,在您的on-click事件中,您的代码最终会在指针#2处调用函数。