首页 > 解决方案 > 想要使用 jquery 获取 url 特定值

问题描述

对于标签 "https://www.test.com/brand/product_name" 中的所有产品,我都有这样的网址。我想获得一个标签的 product_name 点击。

我不知道如何做到这一点。如果有人有想法,请告诉我。

我的代码html如下:

<div class="card_caption"> 
<a href="https://www.test.com/brand/product_name" class="more-btn" target="_blank" style="background:#; color:#">know more</a>
</div>

js代码如下:

jQuery('.card_caption a').click(function(){
     console.log("working_fine");
    var href = $(this).attr('href');
});

https://www.test.com/brand/product_name

点击标签,我只想在变量中获取 product_name 。任何人有想法然后让我知道。

标签: htmljquery

解决方案


如果您split使用作为分隔符的数组路径,forward-slash您只需使用pop()方法获取数组中的最后一个元素。

jQuery('.card_caption a').click(function(){
     console.log( $(this).attr('href').split('/').pop() )
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card_caption"> 
  <a href="https://www.test.com/brand/product_name" class="more-btn" target="_blank" style="background:#; color:#">know more</a>
</div>
Js code as follows:


推荐阅读