【问题标题】:jQuery draggable(), on drag perform a dynamic functionjQuery draggable(),在拖动时执行动态功能
【发布时间】:2010-08-23 16:57:19
【问题描述】:

我有一个 jQuery draggable() 函数,并且在拖动时正在执行基于 if 的其他几个函数。像这样的:

$("div.element").draggable({
    drag: function() {
            if  (a=1){
                function1();
                }
            if  (a=2){
                function2();
                }   
            if  (a=3){
                function3();
                }   
    }
});

涉及到许多变量,我希望从性能角度对此进行优化。是否可以让可拖动的“知道”在拖动时执行什么功能,而无需每次都进行if 检查。像拖动这样的东西只是 function2() 和 function3()。

谢谢

【问题讨论】:

  • 什么决定了应该运行哪个函数?
  • 一个 .attr 请求; if ($("someElement").attr("fontsize")){do this function},还不确定如何验证一个attr是否存在,但这就是想法......
  • 这并没有真正解释在什么情况下应该运行什么函数。
  • 好的,也许这应该更好地解释: if ($("#layer0").hasClass("fontsize")){ function1(); } if ($("#layer0").hasClass("color")){ function2(); } if ($("#layer0").hasClass("lineheight")){ function3(); }
  • 很抱歉无法更好地解释它。在拖动元素时,该函数将检查其他元素是否具有某些属性或类,并据此执行某些函数

标签: jquery draggable


【解决方案1】:

您可以使用 jQuery 数据将适当的函数对象与可拖动元素一起存储:

// declare the appropriate function for each element
$("select elements that need function1").data("dragFunction", function() {
  // whatever
});
$("select elements that need function2").data("dragFunction", function() {
  // whatever
});

// and then... just execute whatever function is stored in "dragFunction"
$("div.element").draggable({
  drag: function() { return $(this).data("dragFunction")(); }
});

【讨论】:

  • 不太确定它是否适用于我的情况,但我会试一试并告诉你
  • @Mircea:也许这不是您所需要的,但另一方面:我认为您在这里进行了过早的优化。用例(用鼠标手动拖动元素)并不是很重的负载。一些未使用的if 语句不会减慢它的速度。
猜你喜欢
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-02
  • 2020-07-19
  • 2012-07-02
  • 1970-01-01
  • 2020-06-25
相关资源
最近更新 更多