【问题标题】:Call an internal function of a jQuery plugin? Or how to ignore callback calls from a jQuery plugin?调用 jQuery 插件的内部函数?或者如何忽略来自 jQuery 插件的回调调用?
【发布时间】:2015-06-10 18:30:31
【问题描述】:

编辑

可以调用jQuery插件的内部函数吗?

我需要调用color picker sliderupdateColor 函数,而不是它触发的onchange 回调。

我可以使用$('#colorpicker').trigger("colorpickersliders.updateColor",color),但这不会立即调用updateColor

如果我可以直接调用 updateColor 函数,我可以在调用之前取消设置 onchange 回调并在之后重置它:

$('#colorpicker').ColorPickerSliders(onchange:function(){}) // disable my *onchange* callback
// --- a trick to call updateColor immediately --- //
$('#colorpicker').ColorPickerSliders(onchange:MyNormalOnChangeCallback) // enable my *onchange* callback

原问题

我使用color picker slider,它是一个 jQuery 插件。我设置了 onchange 回调函数来响应更改。

问题是当我想以编程方式改变颜色的值时,我想避免回调被调用。

我可以有一个标志(甚至是一个计数器)来忽略我的 onchange 回调的调用,但我不太喜欢这种方法。

Here 是一个说明我的问题的 plunkr:

  var solution1 = false;   // set this to true for the dirty solution
  var ignoreCounter = 0;

  // the onchange callback
  onchange = function(container, color) {
    // I would like to print the color only if it was set manually by the user, not programatically

    if(solution1 && ignoreCounter>0)    // dirty solution: ignore the call if ignoreCounter is greater than 0
    {
      ignoreCounter--;
      return;
    }

    console.log("color: " + color.tiny.toRgbString());
  }

  // initialize ColorPickerSliders
  $('#colorpicker').ColorPickerSliders( { onchange: onchange, flat: true } )

  // set the color programmatically
  setInterval(function(){
    ignoreCounter++; // ignore callback next time
    $('#colorpicker').trigger("colorpickersliders.updateColor", "rgb(0,0,"+(Math.random()*255)+")");
  }, 1000)

你会怎么做?有没有办法修改一个jQuery插件?

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    当个人事件函数返回 false 时,会阻止事件的自然回调。

    var onchange = function(container, color) {
    
        if(solution1 && ignoreCounter>0),{
          ignoreCounter--;
          return false;
        }
    
        console.log("color: " + color.tiny.toRgbString());
    
        return false;
      }
    

    【讨论】:

    • 谢谢,但这不是我要找的:我想忽略我自己的自定义 onchange 回调。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多