2015-05-18 66 views
-1

我有一個鏈接(mysite.com/#page-1,#page-2 ...)。我希望分別將其更改爲/ page-1,/ page-2(# - > /)。 這可能嗎?更改懸停部分的Href jQuery的

我試圖走這條路:

$('.page-link').hover(function() { 
    var text = $(this).href(); 
    $(this).href(href.replace('#', '')); 
}); 
+0

'href.replace'應該是'text.replace'必要的分頁。 – Barmar

回答

0

首先,.hover需要功能;一個用於in,一個用於out

$('.page-link').hover(

    // mousein 
    function() { 

    // cache the original href 
    $(this).data("href", $(this).attr("href")); 

    // replace the existing href 
    $(this).attr("href", function(idx, val) { 

     // regexp match the page number 
     // $1 will be set to literal string "#page-" 
     // $2 will be a string of the page number 
     return val.replace(/(#page-)(\d+)$/, function(str, $1, $2) { 

     // parse as int and increment by 1 
     return $1 + (parseInt($2, 10) + 1); 
     }); 
    }); 
    }, 

    // mouseout 
    function() { 

    // restore the original href from the "cache" 
    $(this).attr("href", $(this).data("href")); 

    // clear the cache 
    $(this).data("href", null); 
    } 
); 

演示時間,對嗎?

$('.page-link').hover(
 
    function() { 
 
    $(this).data("href", $(this).attr("href")); 
 
    $(this).attr("href", function(idx, val) { 
 
     return val.replace(/(#page-)(\d+)$/, function(str, $1, $2) { 
 
     return $1 + (parseInt($2, 10) + 1); 
 
     }); 
 
    }); 
 
    }, 
 
    function() { 
 
    $(this).attr("href", $(this).data("href")); 
 
    $(this).data("href", null); 
 
    } 
 
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<a href="#page-1" class="page-link">next page</a> 
 
<a href="#page-2" class="page-link">next page</a> 
 
<a href="#page-50" class="page-link">next page</a>

如果你有href#page-N部分之前的內容,如:

<a href="blahblah/#page-1">...</a> 

您需要調整.replace調用此

return val.replace(/^(.*#page-)(\d+)$/, function(str, $1, $2) { 
    return $1 + (parseInt($2, 10) + 1); 
}); 

這將確保更新整個href(不只是由#page-N部分取代)。如果JavaScript RegExp支持lookbehind,則可避免此類煩惱,但可悲的是它不支持。


所有這一切說壽,你應該計算,而不是試圖弄明白後的,實際上在HTML

+1

完美答案。那真的很有幫助。謝謝! – Arriba