获取属性表格Next& Prev div使用Jquery

时间:2013-07-31 16:09:42

标签: jquery

我正在尝试一个示例来学习如何从下一个&获取“标签”的属性“href”。 prev div's。考虑我点击div id =“rw2”中的'a tag',我需要在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'

2 个答案:

答案 0 :(得分: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");
});

答案 1 :(得分: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'