2014-01-24 130 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"); 
});