jQuery动态设置href属性

时间:2014-01-24 18:32:43

标签: jquery attributes set

我正在建立一个电子商务网站。

当产品列表从数据库加载时,将它们添加到购物车的链接如下所示(每个产品):

<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 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

试试这个:

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