-1

我正在尝试一个示例来学习如何从下一个和上一个 div 中获取“a tag”的属性“href”。考虑我单击 div id="rw2" 中的“a 标签”,我需要在 prev div#rw1 和 next div#rw3 中获取标签的 href。

  <div class="plist" id="rw1">
    <div class="image">
         <a href="1.html">1</a>
    </div>
    <div class="some"></div>
    <div class="few"></div>
  </div>

  <div class="plist" id="rw2">
    <div class="image">
         <a href="2.html">2</a>
    </div>
    <div class="some"></div>
    <div class="few"></div>
  </div>

   <div class="plist" id="rw3">
    <div class="image">
         <a href="3.html">3</a>
    </div>
    <div class="some"></div>
    <div class="few"></div>
  </div>

   ......

期待结果

#rw1 .image a clicked - next = '2.html' & Prev = ''

#rw2 .image a clicked - next = '3.html' & Prev = '1.html'
4

2 回答 2

2

尝试:

$(".plist .image a").click(function() {
    var p = $(this).closest(".plist").prev(".plist").find("a").prop("href");
    var n = $(this).closest(".plist").next(".plist").find("a").prop("href");
});
于 2013-07-31T16:12:30.530 回答
0

这将得到你正在寻找的东西,检查这个小提琴http://jsfiddle.net/smerny/BttMH/1/上的控制台:

$(".plist .image a").click( function(e) {
    e.preventDefault(); //to stop page from loading - can remove depending on need
    var $plist = $(this).closest(".plist");
    var thisId = $plist.prop("id");
    var nextLink = $plist.next().find("a").prop("href") || "";
    var prevLink = $plist.prev().find("a").prop("href") || "";
    console.log(thisId + ".image a clicked - next = '"+nextLink+"' & Prev = '"+prevLink+"'");
});

编辑:要得到你想要的结果,试试这个:http: //jsfiddle.net/smerny/BttMH/3/

$(".plist .image a").click( function(e) {
    e.preventDefault(); //to stop page from loading - can remove depending on need
    var $plist = $(this).closest(".plist");
    var thisId = $plist.prop("id");
    var nextLink = $plist.next().find("a").prop("href") || "";
    var prevLink = $plist.prev().find("a").prop("href") || "";
    nextLink = nextLink.substr(nextLink.lastIndexOf('/') + 1); //remove these if you want full url
    prevLink = prevLink.substr(prevLink.lastIndexOf('/') + 1);
    console.log(thisId + " .image a clicked - next = '"+nextLink+"' & Prev = '"+prevLink+"'");
});

单击将记录:

rw1 .image a clicked - next = '2.html' & Prev = ''
rw2 .image a clicked - next = '3.html' & Prev = '1.html'
rw3 .image a clicked - next = '' & Prev = '2.html' 
于 2013-07-31T16:17:58.123 回答