2013-07-31 107 views
-1

我正在嘗試一個示例來學習如何從下一個012vprev div的獲取「標記」的屬性「href」。考慮我點擊div id =「rw2」中的'a tag',我需要在prev div#rw1和next div#rw3中獲取標籤的href。使用jquery獲取屬性表單Next&Prev div使用jquery的

<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

嘗試:

$(".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"); 
}); 
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'