2011-11-29 275 views
5

我有下一個鏈接,讓用戶瀏覽URL列表(存儲在數組中)。當用戶點擊下一個時,我希望鏈接href和錨點更新爲我陣列中的下一個網站。到目前爲止,我嘗試過的方式是每次跳過一個網址,而且我知道爲什麼,它與之前的點擊有關,甚至沒有完成,但是正確的方法是什麼?如何在點擊鏈接時進行鏈接更新?

下面是一個例子,所以你可以看到什麼我談論:http://jsbin.com/atobep

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html> 
<head> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script> 
<script> 


$(document).ready(function(){ 

    var items = []; 
    $.each(urls, function(i, item) { 
     items.push("<li>"+item['name']+"</li>"); 
    }); 

    $('#list').append(items.join('')); 

    changeNextLink(0); 
    $("#frame").attr('src', urls[0]['url']); 

}); 

var urls = [{"name":"ebay","url":"http://ebay.com"},{"name":"amazon","url":"http://amazon.com"},{"name":"msn","url":"http://msn.com"},{"name":"yahoo","url":"http://yahoo.com"},{"name":"wikipedia","url":"http://wikipedia.org"}]; 

function changeNextLink(x){  

    $('#now').html(urls[x]['name']); //show the name of currently loaded page 
    $('#nextLink').html(urls[x+1]['name']); //name of next website as anchor of next link 
    $('#nextLink').attr('href', urls[x+1]['url']); //url to next website 
    $('#nextLink').attr('onclick','changeNextLink('+(x+1)+')'); //the problem spot. prepare next link for next click. 

} 
</script> 
</head> 
<body> 

    <ol id="list"></ol> 

    now: <span id="now"></span> | next: <a href="" target="frame" id="nextLink"></a><br /> 
    <iframe name="frame" src="" id="frame" style="width:500px; height:600px;"></iframe> 

</body> 
</html> 

回答

1

如何添加一個新的變種跟蹤下一環節的num,並添加點擊處理程序#nextLine

$(document).ready(function(){ 
    var nextLinkNum = 0; 
    var items = []; 
    $.each(urls, function(i, item) { 
     items.push("<li>"+item['name']+"</li>"); 
    }); 

    $('#list').append(items.join('')); 

    changeNextLink(nextLinkNum); 
    $("#frame").attr('src', urls[0]['url']); 

    $('#nextLink').click(function() { 
     if (nextLinkNum + 1 < urls.length) 
      changeNextLink(++nextLinkNum); 
    }); 

}); 

function changeNextLink(x){  
    $('#now').html(urls[x]['name']); //show the name of currently loaded page 
    $('#nextLink').html(urls[x+1]['name']); //name of next website as anchor of next link 
    $('#nextLink').attr('href', urls[x+1]['url']); //url to next website 
    $('#nextLink').attr('onclick','changeNextLink('+(x+1)+')'); //the problem spot. prepare next link for next click. 
} 
+0

bug:'$('#nextLink')「)' –

+0

@mmmshuddup - (偉大的用戶名) - 已修復,謝謝 –

+0

@AdamRackis我喜歡這個解決方案的優雅,我很可能會這樣做。你好, – ofko

0

我做你的JavaScript的一些輕微的變化,似乎現在一切正常......

http://jsbin.com/atobep/5/edit

首先它會檢查列表中是否有下一個url,如果不是,則下一個url將設置爲當前url(如果需要,可以將其設置回第一個url)。如果列表中有另一個,則將其設置爲下一個網址。

+0

這裏的問答環節的一部分就是與公衆分享你所做的改變以及爲什麼而不是粘貼鏈接到碼。 – jfriend00