我想在productinfo
div类的最后一个链接旁边获得上面链接的attr href。我尝试了最接近的,但它给了我相同的链接,我按下,我想要上面的一个。我要存储在produs_href
中的链接是来自productinfo
类下的第一个href
的链接。这是我的代码:
<div class="col-sm-4 produse"><!--PRODUS-->
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center">
<a href="/'.$recomand['ID_Produs'].'/'.$recomand['Nume_Prod'].'.php"><img src="/images/produse/'.$recomand['ID_Produs'].'/'.$recomand['Poza'].'" alt="" /></a>
<h2 style="text-decoration: line-through;">'.$recomand['Pret'].' lei </h2><h2>'.$recomand['Pret_Nou'].' lei </h2>
<a href="link produs"><p>'.$recomand['Nume_Prod'].' '.$recomand['Gramaj'].' '.$tip.'</p></a>
<a href="/engine/app/cos.php?id='.$recomand['ID_Produs'].'" class="btn btn-default add-to-cart cos"><i class="fa fa-shopping-cart"></i>Adaugă în coș</a>
</div>
</div>
</div>
</div>
jquery
<script>
$(".cos").click(function(e){
e.preventDefault();
var href = $(this).attr('href');
var produs_href = $(this).closest('a').attr('href');
$.getJSON(href, function(data) {
$.each(data, function(key, val) {
$("#cnt").empty();
$("#test").append('<li>' + val.nume + '</li>')
$("#cnt").append('' + val.cnt +'')
});
});
$('#detalii_prod').modal('show');
alert(produs_href);
});
</script>
使用prev
。此方法获取紧挨在前的同级。
$(this).prev().attr('href');
编辑
从你的评论来看,可以做到这一点的代码是
$(this).closest('.productinfo').find('a:first').attr('href');
您可以使用.prev
var链接=$(this).prev().attr('ref');
现在你可以使用链接了。
您可以这样使用$(this).prev("a").attr("href");
以及更多帮助:获取上一个HTML锚的href值,<a>,使用jQuery
$(".cos").click(function(e){
e.preventDefault();
var text = $(this).parent().find('a:first').attr('href');
alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 produse">
<!--PRODUS-->
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center"> <a href="test.php"><img src="img/Penguins.jpg" height="50" width="50" alt="" /></a>
<h2 style="text-decoration: line-through;">Hello there</h2>
<h2>Anto</h2>
<a href="link produs">
<p>Angeline</p>
</a> <a href="#" class="btn btn-default add-to-cart cos"><i class="fa fa-shopping-cart"></i>Test</a> </div>
</div>
</div>
</div>
试试这个
$(this).parent().find('a:first').attr('href');
尝试使用.eq()
方法。
$(this).parent().find('a').eq(0).attr('href');
希望这能帮助你。。。