2012-04-13 61 views
0

我有一個有序列表增量href的值

<li id="prev"> 
    <a href="#fragment-1>Next</a> 
</li> 

我希望在接下來的點擊就應該從4停止遞增href

<a href="#fragment-1">... 
<a href="#fragment-2">... 
<a href="#fragment-3">... 
<a href="#fragment-4">... 

和回到1 allso是否可能用javascript完成

謝謝

回答

3

G首先您的鏈接id,以便於選擇。

然後,

document.getElementById('the_id_here').addEventListener('click', function(e) { 
    var n = e.target.href.split('-')[1] * 1 + 1; 
    if (n > 4) 
     n = 1; 
    e.target.href = e.target.href.split('-')[0] + '-' + n; 
}, false); 

例子:http://jsbin.com/ajegaf/4#fragment-1

0

不正是你想要的,但應儘量接近瞄準你在正確的方向,檢查http://jsfiddle.net/pj28v/

<ul id="list"></ul> 
<a href="#" id="next">Next</a>​ 

$(function() { 

    var $list = $('#list'), 
     count = 4, 
     i = 0, 
     cur = 0; 

    for (; i < count; i++) { 
     $list.append('<li><a href="#fragment' + i + '">frag' + i + '</a></li>'); 
    } 

    $('a', $list).eq(0).css('color','red'); 

    $('#next').click(function(ev) { 
     ev.preventDefault(); 
     cur++; 
     if (cur >= count) cur = 0; 
     $('a', $list).css('color','blue').eq(cur).css('color','red'); 
    }); 
});​ 
0

一個jQuery的解決方案:

$(document).ready(function(){ 

    $('#prev a').click(function(){ 

     var href = $(this).attr('href'); 
     var num = parseInt(href.substr(href.indexOf('-') + 1)); 

     if(num == 4) 
     { 
      num = 1; 
     } 
     else 
     { 
      num++; 
     } 

     $(this).attr('href', '#fragment-' + num) 
    }); 

});​ 

http://jsfiddle.net/UYDdB/

0

類似於Delan的解決方案之一,但使用jQuery並且沒有使用測試的解決方案。 http://jsfiddle.net/GZ26j/

$('#next').on('click', function(e) { 
    e.preventDefault(); 
    href = $(this).attr('href'); 
    var n = href.split('-')[1] * 1 + 1; 
    n = n%5; 
    e.target.href = href.split('-')[0] + '-' + n; 
});​ 

編輯: 該解決方案使處於0且計數器開始不是1

+0

n%5在達到4後不能正常工作,然後再次從零開始,而不是一次。 – harag 2012-04-13 10:34:56

+0

哦,你是對的,我忘了它應該從1開始。 – TimPetricola 2012-04-13 13:55:45

0

使用隱藏字段來保存的價值,以及一個onclick功能,以增加它並提交表單。請參閱:How can I increase a number by activating a button to be able to access a function each time the button is increased?

<? 

if(!isset($_GET['count'])) { 
    $count = 0; 
    } else { 
    $count = $_GET['count']; 
    } 

    ?> 

    <script type='text/javascript'> 
    function submitForm(x) { 
    if(x == 'prev') { 
    document.getElementById('count').value--; 
    } else { 
    document.getElementById('count').value++; 
    } 

    document.forms["form"].submit(); 
    } 
    </script> 

    <form action='hidfield.php' method='get' name='form'> 
    <input type='hidden' name='count' id='count' value='<?php echo $count; ?>'> 
    </form> 

    <input type='submit' name='prev' value='prev' onclick="submitForm('prev')"> 
    <input type='submit' name='next' value='next' onclick="submitForm('next')">