2013-04-21 77 views
-2

我有一个jquery操作应用于基于一个div(这是我选择div和应用行动,但我的hve 90格)在其ID如何缩写本声明: 以下是代码如何缩写jquery事件?

if ($('#justgarph > p:contains("draggable1")').length > 0) { 
    $(".product").animate({ 
     "top": "0", 
     "left": "0" 
    }, 500).delay(100); 

    $("#draggable1").animate({ 
     "top": "-300px", 
     "left": "200px" 
    }, 500); 

    setTimeout(function() { 
     $("#draggable1").animate({ 
      "top": "-106px", 
      "left": "470px" 
     }, 1000); 
     $("#draggable1").addClass("activeproduct") 
    }, 800); 
} 

if ($('#justgarph > p:contains("draggable2")').length > 0) { 
    $(".product").animate({ 
     "top": "0", 
     "left": "0" 
    }, 500).delay(100); 

    $("#draggable2").animate({ 
     "top": "-300px", 
     "left": "100px" 
    }, 500); 

    setTimeout(function() { 
     $("#draggable2").animate({ 
      "top": "-106px", 
      "left": "320px" 
     }, 1000); 

     $("#draggable2").addClass("activeproduct") 
    }, 800); 
} 
+1

是'left'参数不同的“470px”和“320px” – 2013-04-21 09:27:53

+2

如果是这样的话,你需要它作为第二个参数@ArunPJohny。除非有办法计算'left',否则我的解决方案将不再可能。 – simbabque 2013-04-21 09:29:43

回答

0

你有建立一个循环并使ID动态。如果我正确地看到这个,唯一改变的就是ID。

// make them all draggable 'at once' if they all have the same left values 
for (var i=0; i<90; i++) { 
    if ($('#justgarph > p:contains("draggable"' + i + ')').length > 0) { 
     $(".product").animate({ 
      "top": "0", 
      "left": "0" 
     }, 500).delay(100); 

     $("#draggable" + i).animate({ 
      "top": "-300px", 
      "left": "200px" 
     }, 500); 

     setTimeout(function() { 
      $("#draggable" + i).animate({ 
       "top": "-106px", 
       "left": "470px" 
      }, 1000); 
      $("#draggable" + i).addClass("activeproduct") 
     }, 800); 
    } 
} 

万一改变left值是故意的,你有把整个事情的功能更好。你的代码会比上面的要长一点。但它只能在循环中工作,如果全部相同。

所以在这里,你已经有了三个参数的函数。第一个是id作为#的文本,第二个和第三个是px中的两个变化的left值,没有px

function makeDraggable(id, l1, l2) { 
    if ($('#justgarph > p:contains(' + e + ')').length > 0) { 
     $(".product").animate({ 
      "top": "0", 
      "left": "0" 
     }, 500).delay(100); 

     $(e).animate({ 
      "top": "-300px", 
      "left": l1 + "px" 
     }, 500); 

     setTimeout(function() { 
      $(e).animate({ 
       "top": "-106px", 
       "left": l2 + "px" 
      }, 1000); 
      $(e).addClass("activeproduct") 
     }, 800); 
    } 
} 

// make them all draggable, one at a time 
makeDraggable('#draggable1', 100, 470); 
makeDraggable('#draggable2', 200, 320); 
+0

将不起作用,因为超时部分中的“left”值不同 – 2013-04-21 09:28:19

+0

不起作用:( – Medhat 2013-04-21 10:07:06

+0

这真的不是一个非常有用的评论@Medhat。是否有错误信息?哪部分不起作用?您尝试过播放与它在一起? – simbabque 2013-04-21 20:58:47