2011-11-29 92 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