2014-01-24 127 views
1

我正在製作一個電子商務網站。jQuery設置href屬性動態

當產品列表負載從數據庫的鏈接,將它們添加到購物車看起來像這樣(每個產品):

<a class="addtocart" data-id="<Product ID from the DB>">Add To Cart!</a> 

現在,以後,使用jQuery我加入了更多的類,所以它顯示Fancybox窗口中的內容。

//Links with the class Fancybox upens in a nice modal window 
$(".addtocart").addClass("fancybox"); //This Works 

//Then, the window should show this page: addtocart.php, but not before sending a GET parameter so it knows Which product it is adding to the shopping cart 
var href = "addtocart.php"; 
$(".addtocart").attr("href", href + "?id=" + $(this).attr("data-id")); 

的最後一行代碼是不工作...它顯示在最後一個像這樣的鏈接:

<a data-id="10" class="addtocart fancybox" href="addtocart.php?id=undefined">Add to Cart!</a> 

但應顯示HREF部分是這樣的:

href="addtocart.php?id=10" 

我已經嘗試了很多,它不起作用。謝謝您事先

回答

2
$(".addtocart").each(function() { 
    $(this).attr("href", "addtocart.php?id=" + $(this).attr("data-id")); 
}); 
+0

魔術,謝謝你,我怎麼能忘了每樣東西? – JuanBonnett

0

試試這個:

$(".addtocart").prop("href", function() { 
    return "addtocart.php?id=" + $(this).data("id"); 
});