2010-12-10 83 views
1

我願做以下的號召建立一個jQuery插件動態建立呼叫的jQuery插件

jQuery("#wrapper").myPLugin({ 
    direction: direction, 
    switch myOption 
    { 
     case "small": 
     items:10, 

     case "big": 
     items:25, 

    } 
    switch otherOption 
    { 
     case "small": 
      prev: { 
      button: buttonPrev, 
      key: "left" 
     }, 

     case "big": 
      prev: { 
      button: buttonPrev, 
      key: "left" 
     }, 

    } 
    pagination: ".paginationHolder" 
}); 

顯然,這是不行的,但什麼是這幾樣集結的最佳途徑,有動態建立到jQuery插件這樣

+0

你是什麼意思的「」動態建立一個調用jQuery插件「」? – rahul 2010-12-10 08:54:19

+0

正如你可以看到上面,我想有開關,如果語句等,並基於通過一個不同的選項,所以(在上面的例子中)我通過10或25項目到這個特定的插件調用 – nokiko 2010-12-10 08:57:44

回答

1

選項調用的一般方法1

三元運算符是你的朋友

condition ? trueResult : falseResult 

所以你的情況可能是

jQuery("#wrapper").myPLugin({ 
    direction: direction, 
    items: myOption == "small" ? 10 : myOption == "big" ? 25 : 0, // or some default value 
    prev: otherOption == "samll" ? {button: prevButton, key: 'left'} : otherOption == "big" ? {button: prevButton, key: 'left'} : null, 
    pagination: ".paginationHolder" 
}); 

選項2

另一種方法是建立你的對象調用的外部,畢竟JavaScript對象是完全dynamicallly類型:

var setup = new object(); 
setup.direction = "foo"; 
switch(myOption){ 
    case "small": 
    setup.items = 10; 
    break; 
    case "big": 
    setup.items = 25; 
    break; 
} 
switch(otherOption){ 
    case "small": 
    setup.prev = {button: prevButton, key: 'left'}; 
    break; 
    case "big": 
    setup.prev = {button: prevButton, key: 'left'}; 
    break; 
} 
setup.pagination =".paginationHolder" 

jQuery("#wrapper").myPLugin(setup); 
+0

有趣的是,這也適用於超過2個選項 – nokiko 2010-12-10 09:00:56

+0

與其他選項編輯它,我將如何建立動態設置的設置。 – nokiko 2010-12-10 09:14:04

+0

@nokiko - 查看更新的答案。如果這是越來越複雜的使用選項2。 – Jamiec 2010-12-10 09:32:18