使用jquery ajax更改运行时的href attr

时间:2013-09-14 15:40:56

标签: ajax jquery

我有一个传递给jQuery AJAX的URL。

<a href="/wishlist.php?sku=C5&amp;action=move&amp;qty=1" class="buttoncart black">Move To Wishlist</a>;

当它到达AJAX时,我希望将href属性更改为

<a href="/ajax_page.php?sku=C5&amp;action=move&amp;qty=1">Move blaf</a>

我还是个新手。我确定必须有一个简单的方法。这是我的剧本。

var wishorder = {
    init: function(config){
        this.config = config;
        this.bindEvents();
    },
    bindEvents: function(){
        this.config.itemSelection.on('click',this.addWish);
    },
    addWish: function(e){
        console.log('working');
        console.log($(this).attr('href').pathname);
        var self = wishorder;

        $.ajax({
            //this is where im using the href and would like to change it
            //but i cant seem to access to get variables
            url: $(this).attr('href'),
            //url: '/ajax/ajax_move.php',
            type: 'GET',
            data: {
                sku: $(this).data('sku'),
                action: $(this).data('action'),
                qty: $(this).data('qty')
            },
            success: function(results){
                console.log(results);
                $('#cartcont').html(results);
            }
        });
        e.preventDefault();
    }
};
wishorder.init({
    itemSelection: $('#carttable tr a'),
    form: $('#cartfrm')
});

2 个答案:

答案 0 :(得分:2)

您可以在replace逻辑中使用addWish来更改网址:

addWish: function(e){
    var self = wishorder;
    var url = $(this).attr('href').replace('wishlist.php', 'ajax_page.php');

    $.ajax({
        url: url ,
        type: 'GET',
        data: {
            sku: $(this).data('sku'),
            action: $(this).data('action'),
            qty: $(this).data('qty')
        },
        success: function(results){
            console.log(results);
            $('#cartcont').html(results);
        }
    });
    e.preventDefault();
}

答案 1 :(得分:1)

你只需要换一个字符串。

var original_href = $('<a href="/wishlist.php?sku=C5&amp;action=move&amp;qty=1" class="buttoncart black">').attr('href');

var new_href = original_href.replace(/wishlist.php/, "ajax_page.php");