繁体   English   中英

如何使用jQuery获取href值?

[英]How to get href value using jQuery?

我正在尝试使用 jQuery 获取 href 值:

<html>
    <head>
        <title>Jquery Test</title>
         <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
            $("a").click(function(event) {
                alert("As you can see, the link no longer took you to jquery.com");
                var href = $('a').attr('href');
                alert(href);
                event.preventDefault();
            });
        });
        </script>
    </head>
    <body>
        <a href="http://jquery.com/">jQuery</a>
    </body>
</html>

但它不起作用。 为什么?

你需要

var href = $(this).attr('href');

在 jQuery 单击处理程序中, this对象指的是单击的元素,而在您的情况下,您总是获得页面上第一个<a>的 href 。 顺便说一句,这就是为什么您的示例有效但您的真实代码无效的原因

您可以通过以下代码获取当前的 href 值:

$(this).attr("href");

通过ID获取href值

$("#mylink").attr("href");

值得一提的是

$('a').attr('href'); // gets the actual value
$('a').prop('href'); // gets the full URL always

它有效...在 IE8 中测试(如果您正在测试计算机上的文件,请不要忘记允许 javascript 运行)和 chrome。

如果页面有一个<a>可以,但是,很多<a>必须使用var href = $(this).attr('href');

**Replacing  href attribut value to other** 
 
 <div class="cpt">
   <a href="/ref/ref/testone.html">testoneLink</a>
 </div>

  <div class="test" >
      <a href="/ref/ref/testtwo.html">testtwoLInk</a>
  </div>

 <!--Remove first default Link from href attribut -->
<script>
     Remove first default Link from href attribut
    $(".cpt a").removeAttr("href");
    
    Add  Link to same href attribut
    var testurl= $(".test").find("a").attr("href");
    $(".test a").attr('href', testurl);
</script>

如果你的html链接是这样的:

<a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>

然后你可以访问jquery中的href,如下所示(不需要在href中使用“a”)

$(".linkClass").on("click",accesshref);

function accesshref()
 {
 var url = $(".linkClass").attr("href");
 //OR
 var url = $(this).attr("href");
}
<a class ="linkClass" href="https://stackoverflow.com/"> Stack Overflow</a>

$(".linkClass").click(function() {
                alert($(this).attr("href"));
            });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM