0

我正在处理一些列表项和 readicon 类单击我无法捕获带有类书路径的 href 值。在这种情况下(google.com)
这里是代码

<li >
  <div class="overlay">
  <span id="Title">Yeah Dude</span>
  <img class="readIcon" src="images/read.png" />
  </div>
 <a class="bookPath" href="http://www.google.com"><img src="images/bookCovers/asp.net4.5.jpg"  alt="book" /></a></li>

我试过这段代码,但它返回未定义。

$(document).ready(function () {
$(".overlay .readIcon").click(function () {
    //    $(this).('href', 'index.html');
    var bookPath = $(this).parents('li').closest('a').href;
    alert(bookPath);


});});

多谢。

4

5 回答 5

1

将您的查询更改为:

$(document).ready(function () {
    $(".overlay .readIcon").click(function () {
        var bookPath = $(this).parents('li').children('a').attr('href');
        alert(bookPath);
    });
});

小提琴:http: //jsfiddle.net/Lbr4z/

于 2013-03-14T16:58:49.443 回答
0

获取 href 属性值。用于closest获取外里并用于find获取锚点

var bookPath = $(this).closest('li').find('a').attr("href");

Jsfiddle 示例:http: //jsfiddle.net/4QGHS/5/

另外,在做 jQuery 选择器时,尽量做到更具体find('a')将返回所有锚标签。所以你最好使用你正在寻找的元素的类名。试着给你的li元素一个类。

<li class='bookItem'>
  <div class="overlay">
  // your other html goes here 
   <img class="readIcon" src="someImage.jog" /> 
  </div>
  <a class="bookPath" href="http://www.google.com"></a>
</li>

现在你的 javascript 将是

$(function(){

 $(".overlay .readIcon").click(function (e) {
    e.preventDefault();  //prevent as needed.
    var bookPath = $(this).closest('li.bookItem').
                                            find('a.bookPath').attr("href");
    alert(bookPath);
 });

});

Jsfiddle 示例http://jsfiddle.net/4QGHS/9/

于 2013-03-14T16:56:13.980 回答
0

使用$(selector).attr("href");:)

于 2013-03-14T16:56:53.893 回答
0

有很多方法可以做到这一点,这就是其中之一。

 $(document).ready(function () {

    $(".overlay .readIcon").click(function () {
        //    $(this).('href', 'index.html');
        var bookPath = $(this).parent().parent().find("a.bookPath").attr("href");
        alert(bookPath);


    });
});
于 2013-03-14T17:05:32.303 回答
0

尝试.siblings()

var bookPath = $(this).parent().siblings('a').attr('href');

尝试.find()

var bookPath = $(this).closest('li').find('a').attr('href');

如果您想更具体,那么:

var bookPath = $(this).closest('li').find('a.bookPath').attr('href');
于 2013-03-14T17:09:58.530 回答