2011-01-19 17 views
0

「閉じる」divをクリックすると、「基本テキスト」が表示されません。 要するに、第2の「クリック」機能を使用しないのはなぜですか?jquery:2つのクリック機能

<!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にまだ作成されていない要素にバインドされることを許可します。

関連する問題