2012-10-11 153 views
0

我有一段HTML代碼,當單擊鏈接時,div內容將成爲鏈接的div內容。第一個功能正常工作。這是第二次點擊#hidelink,jQuery似乎沒有迴應。我在這裏錯過了什麼?jQuery .click功能不起作用

<div id="right"> 
    <div id='titletext'><p>||||||||||||||</p></div> 
    <div id='presentation'></div> 

    <div class='hidethisdiv'> 
     <div id ="years"> 
      <h4><a id='resourceslink' href='#resources'>2010 Presentations</a></h4> 
     </div> 
     <div id='resources'>  
      <h4><a id='resourceslink' href='#resources'>2010 Presentations</a></h4> 
      <p><a id='hidelink' href='#years'>&laquo;--back</a></p> 
     </div> 
    </div> 
</div> 

<script type="text/javascript">// <![CDATA[ 
    $('#mainmenu').fadeIn(2000, function() { 
    // Animation complete. 
    }); 

$('#presentation').html($('#years').html()); 

$(function() { 
    $("#resourceslink").click(
    function() { 
    $('#presentation').html($('#resources').html()); 
    } 
    ); 

    $("#hidelink").click(
    function(){ 
    $('#presentation').html($('#years').html()); 
    } 
); 
    //just add more divs like resources and a hidelink for new conferences 
}); 
</script> 
+0

好像你上次'$(函數(){...'塊嘗試刪除'$(function()'部分,然後運行'$(「resourceslink).click(...)'。如果需要打包,請嘗試'($(function(){ ...})()'希望有幫助,而且'id'不能分配多次,請使用'class'來代替。 – VKen

回答

0

在你的代碼所示,你有ID和價值之間的空間;)也,ID是唯一的,這樣不必使用id =「resourceslink」一個的是不好的做法:)

0

使用$('#resources').html()元素被轉換爲html。您稍後再閱讀它。問題是,您將綁定單擊事件到#hidelink befor html被解析。事件鏈接到隱藏的元素。

將內容添加到#presentation之後,一種解決方案可能會鏈接單擊事件。另一個問題是#hidelink在將html添加到#presentation之後不再是唯一的。

更好的解決方案是不使用.html()。將所有元素添加到#presentation並用display: none隱藏它們。然後綁定單擊事件,並使用.show().hide()顯示#years#resources

例子:

<div id="right"> 
    <div id='presentation'> 
     <div id ="years"> 
      <h4><a id='resourceslink' href='#resources'>2010 Presentations</a></h4> 
     </div> 
     <div id='resources' style="dislay: none">  
      <h4><a id='resourceslink' href='#resources'>2010 Presentations</a></h4> 
      <p><a id='hidelink' href='#years'>&laquo;--back</a></p> 
     </div> 
    </div> 
</div> 


$("#resourceslink").click(function() { 
    $('#resources').show(); 
    $('#years').hide(); 
}); 

$("#hidelink").click(function() { 
    $('#resources').hide(); 
    $('#years').show(); 
}); 
+0

爲什麼會發生這種情況,我該如何解決? – alrightgame

1

您可以使用jQuery的隱藏和下面顯示也。

$("#hidelink").live('click',function() { 

$('#resources').hide(); 

$('#years').show(); 

}); 

如果您正在使用Firefox作爲瀏覽器,你可以使用螢火蟲是一種添加on.By把破發點上的腳本中使用螢火蟲將讓你在什麼地方出了錯的想法。

希望這會幫助你。

+0

不要使用.live(),它已被棄用:http://api.jquery.com/live/,它根本就不是高性能的。 – Aktee

1

首先,ID是唯一的。它只能存在一次!在你的例子中有2個resourceslink。

如果您有多個要分組的元素,請使用類。提醒:每個元素可以有多個類!例如

<a href="#hey" class="testing hello">heyhey</a> 

您可以

$(".testing") - or - $(".testing.hello") - or - $(".hello") 

稱之爲並附事件監聽器這樣

$(".testing").on("click", function() { 
    doThis(); 
})