从<a href=""> click using attribute as a variable

时间:2016-12-09 20:19:44

标签: javascript jquery ajax

I have a link

<a id="container" value="{$variable}" href="#">Click This</a>

That I would like to use to POST via an AJAX call.

Here is my code.

$('#container').click(function(event){
   event.preventDefault();
   $.post('/cart.php?mode=add&productid={$variablegoes here}&amount=1&redirect_from_cart=Y', function(response){
      alert(response);
   });
});

1 个答案:

答案 0 :(得分:3)

简单,只需读取属性,使用encodeURIComponent进行编码,然后将值连接到字符串中。

$('#container').click(function(event){
    event.preventDefault();
    var variable = $(this).attr('value');
    $.post('/cart.php?mode=add&productid=' + encodeURIComponent(variable) + '&amount=1&redirect_from_cart=Y', function(response){
        alert(response);
    });
});

a标记通常不具有value属性,因此我建议使用数据属性来保持HTML的良好和有效。

<a id="container" data-value="{$variable}" href="#">Click This</a>
$('#container').click(function(event){
    event.preventDefault();
    var variable = $(this).attr('data-value');
    $.post('/cart.php?mode=add&productid=' + encodeURIComponent(variable) + '&amount=1&redirect_from_cart=Y', function(response){
        alert(response);
    });
});