2011-01-19 79 views
0

爲什麼我點擊「關閉」div,不顯示「基本文本」?總之,爲什麼不工作第二個「點擊」功能?jquery:雙擊功能

<!DOCTYPE html> 
    <html> 
    <head> 
     <script src="http://code.jquery.com/jquery-1.4.4.js"></script> 
     <script type="text/javascript"> 
     $(document).ready(function(){ 
      $("#sp").click(function(){ 
       $("#info").html("<div><div id='close'>Close</div><div>new text</div></div>"); 
      }); 

      $("#close").click(function(){ 
       $("#info").html("<div>basic text</div>"); 
      }); 
     }); 
     </script> 
     <style> 
     </style> 
    </head> 
    <body> 
    <p id="sp">Click</p> 
    <div id="info"> 
     <div>basic text</div> 
    </div> 
    </body> 
    </html> 

回答

3

您將需要此功能live()

$("#sp").click(function(){ 
    $("#info").html("<div><div id='close'>Close</div><div>new text</div></div>"); 
}); 

$("#close").live('click', function(){ 
    $("#info").html("<div>basic text</div>"); 
}); 

單擊事件處理程序已連接(更不要在這種情況下)後,將創建你的id爲closed元素。您需要確保它也會附加到動態創建的元素。爲此,您可以使用live()

0

事件冒泡,因此您可以直接在info上放置一個處理程序,該程序尋找點擊ID爲close的元素。

$(document).ready(function(){ 
    $("#sp").click(function(){ 
     $("#info").html("<div><div id='close'>Close</div><div>new text</div></div>"); 
    }); 

    $("#info").click(function(e){ 
     if(e.target.id === "close") { 
      $(this).html("<div>basic text</div>"); 
     } 
    }); 
}); 

作爲替代方案,您可以使用delegate()(docs),它基本上是一樣的東西。

$(document).ready(function(){ 
    $("#sp").click(function(){ 
     $("#info").html("<div><div id='close'>Close</div><div>new text</div></div>"); 
    }); 

    $("#info").delegate('#close','click',function(e){ 
     $(this).parent().html("<div>basic text</div>"); 
    }); 
}); 

最終,最好的解決辦法是讓所有頁面上的標記加載時,只是show()(docs)hide()(docs)它是必要的。這比銷燬和重新創建可重用內容要好得多。

0

因爲設置點擊時關閉不存在。改用直播功能。

$("#close").live("click", function(){ 
    $("#info").html("<div>basic text</div>"); 
}); 
0

因爲close元素是動態添加的,並且在頁面加載時不存在於DOM中。

如果您修改代碼一點,以:

$("#close").live('click', 
    function(){ 
     $("#info").html("<div>basic text</div>"); 
}); 

它應該工作的罰款。

live()允許將事件綁定到尚未在DOM中創建/呈現的元素。