[英]How to select “a” tag has specific file type in href using jQuery?
[英]How to select a tag via href in jquery
我已經搜索了。 但這與對方的問題不同。 我想要的是使用href
屬性選擇一個<a>
標記。 請在下面查看我的代碼:
<div class="jump-to">
<ul>
<li>No a</li>
<li class="with-a">
<a href="hello1">Has a</a>
</li>
<li class="with-a">
<a href="hello8">Has a</a>
</li>
<li class="with-a">
<a href="hello10">Has a</a>
</li>
</ul>
</div>
var current_anchor = window.location.href;
var left_anchor = $(".jump-to ul li.with-a a[href="+ current_anchor +"]").prev("li a").attr("href");
alert(left_anchor);
通過href
屬性進行的選擇工作正常。 問題是因為您的DOM遍歷不正確。
由於li
不是同級,因此prev('li a')
對a
無效。 您需要首先使用closest('li')
來獲取父對象,然后使用prev()
,然后使用find('a')
,如下所示:
var current_anchor = 'http://localhost/myproject/hello8'; var left_anchor = $('.jump-to ul li.with-a a[href="' + current_anchor + '"]').closest('li').prev('li').find('a').attr('href'); console.log(left_anchor);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="jump-to"> <ul> <li>No a</li> <li class="with-a"> <a href="http://localhost/myproject/hello1">Has a</a> </li> <li class="with-a"> <a href="http://localhost/myproject/hello8">Has a</a> </li> <li class="with-a"> <a href="http://localhost/myproject/hello10">Has a</a> </li> </ul> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.