2013-04-17 48 views
1

參數content的值應該是一個獲取內容的函數。我以爲我可以使用這樣的事情:函數的返回值作爲jQuery中參數的值

$(".fancy-detail-page").fancybox({ 
     'content' : function(){ 
      var id = $(this).attr('id'); 
      id = id.replace("pd", "c"); 
      var content = $('#' + id + ' .product-details').html(); 
      return content; 
     }, 
     'padding' : 0, 
     'openEffect' : 'none', 
     'closeEffect' : 'none', 
     'maxWidth' : 960 
}); 

return似乎並不奏效。這是如何正確完成的?

+2

將它包裹在括號狀(函數(){...回報內容})()工作? – 2013-04-17 14:57:28

+0

@jqueryrocks:No. – testing

+1

@testing它應該在這裏:http://jsfiddle.net/s6ZKT/ –

回答

0

假設這是同一個插件。

每個API看起來像'內容'必須是數據。

「內容強制內容(可以是任意的HTML數據)」 http://fancybox.net/api

所以,你只需要初始化的fancybox之前調用的函數(或設置內容VAR);

var id = $(this).attr('id'); 
id = id.replace("pd", "c"); 
var content = $('#' + id + ' .product-details').html(); 

$(".fancy-detail-page").fancybox({ 
     'content' : content, 
     'padding' : 0, 
     'openEffect' : 'none', 
     'closeEffect' : 'none', 
     'maxWidth' : 960 
}); 
+0

這裏的問題是'id'屬性。也許它會通過定義一個自己的函數來工作。我會試試看。 – testing

1

感謝jqueryrocks和烤。該解決方案爲我工作:

$(".fancy-detail-page").click(function(e){ 
    e.preventDefault(); 
    var id = $(this).attr('id'); 
    $.fancybox({ 
     'content' : (function(){ 
     id = id.replace("pd", "c"); 
     var content = $('#' + id + ' .product-details').html(); 
     return content; 
     })(), 
     'padding' : 0, 
     'openEffect' : 'none', 
     'closeEffect' : 'none', 
     'maxWidth' : 960 
    }); 
    }); 
1

沒有複雜的東西太多了,你也可以使用的beforeLoad回調得到相同的結果,而這本來是更清潔,更簡單,更快,如:

$(".fancy-detail-page").fancybox({ 
    padding: 0, 
    openEffect: 'none', 
    closeEffect: 'none', 
    maxWidth: 960, 
    beforeLoad : function() { 
     var id = $(this.element).attr("id").replace("pd", "c"); 
     this.content = $('#' + id + ' .product-details').html(); 
    } 
}); 

JSFIDDLE

這行

this.content = $('#' + id + ' .product-details').html(); 

可以降低到這個

this.content = $('#' + id + ' .product-details'); 

沒有必要的.html()得到同樣的結果......看到 updated JSFIDDLE