如何使用jquery在链接中传递ID

时间:2017-03-30 04:15:13

标签: jquery html

我现在有一本书按钮,当用户点击书籍时,他应该被重定向到订单确认页面。我想使用jquery在url中传递type和id。 想通过这种网址 - http://localhost/company/order-confirmation?type=course&id=35

我怎样才能在jquery中做到这一点。

HTML:

 <a href="" class="book_now" batch-id="">Book Now</a>

Jquery的:

  $('.book_now',template).attr('batch-id', val['batch_id']);

4 个答案:

答案 0 :(得分:0)

您可以动态地将href传递给锚点,如:

$('.book_now').attr('href', 'url link');

答案 1 :(得分:0)

您可以为此任务使用数据属性,例如

 <a href="" class="book_now" data-id="11">Book Now</a>

和js代码

var order_id= $('.book_now').data("id");

但是为什么在这里使用如果你想通过jquery发送数据,我认为最好在这里使用按钮。

希望有所帮助。

答案 2 :(得分:0)

请看一下,与你想要的一样

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <title></title>
</head>

<body>
  <a href="/abc" class="book_now" batch-id="123">Book Now</a>
</body>
<script type="text/javascript">
$(".book_now").click(function(e) {
  e.target.href += "?id=" + $(this).attr('batch-id');
})
</script>

</html>

答案 3 :(得分:0)

您应该使用属性数据*(see this link),因为属性“batch-id”不是有效的html。

在常规jQuery中,如果链接是这样提供的:

<a href="http://localhost/company/order-confirmation?type=course" class="book_now" data-batch-id="123">Book Now</a>

我会这样做:

$(document).on('click', '[data-batch-id]', function(e) {
       // Disable link behavior
       e.preventDefault();
       
       // Save information
       var batchID = $(this).data().batchId,
           href    = $(this).attr('href');
       
       // Check if any ID is aviable 
       if (batchID) {
          // Save the url and perform a page load
          var link = href + '&id=' + batchID;
          window.open(link, '_blank');
 
       } else {
          // Error handling
          alert('Can\'t find course, no ID provided')
       }
       
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="http://localhost/company/order-confirmation?type=course" class="book_now" data-batch-id="123">Book Now</a>