开发者

jQuery draggable(), on drag perform a dynamic function

I have a jQuery draggable() function and on drag is executing several other functions based on an if. Something like this:

$("div.element").draggable({
    drag: function() {
            if  (a=1){
                function1();
                }
            if  (a=2){
                function2();
                }   
开发者_高级运维            if  (a=3){
                function3();
                }   
    }
});

There are many variables involved and I am looking to optimize this from the performance perspective point of view. Is it possible to make the draggable "know" what function to perform on drag without doing the if checking each time. Something like on drag do just function2() and function3().

Thank you


You could use jQuery data to store the appropriate function object right with the draggable elements:

// 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")(); }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜