0

jquery.load を使用して div にロードした html ファイル内のコンテンツにアクセスしようとしています。

私のインデックスページは次のようになります。

<!DOCTYPE html>
  <html>
    <head>
       <title>
       </title>
       <script src="jquery.js" type="text/javascript"></script>
       <script src="script.js" type="text/javascript"></script>
       <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <div id="content">
        </div>  
    </body>
</html>

これまでの私のスクリプトは次のようになります。

$(document).ready(function() {
    $("#content").load("content.html");
    $("#content").click(function(){
        alert($(this).attr("id"));
    });
});

content.html ページ:

<!DOCTYPE html>  
<html >  
    <head>
        <title></title>  
    </head>  
    <body>  
        <h1 id="header1">
        Content
        </h1>
        <p>
            This is a paragraph
        </p>
        <p>
            This is another paragraph
        </p>
    </body>
</html>       

つまり、コンテンツ div のタグをクリックすると、そのタグの ID、つまり「header1」が表示されますが、現在は「コンテンツ」が表示されているだけです。どうすればこれを達成できますか?

前もって感謝します

4

1 に答える 1

3

イベント ハンドラーをコンテンツ内のすべての要素にバインドします。

$(document).ready(function() {
    $("#content").load("content.html");
    $("#content, #content *").click(function(e){
         alert(this.id);
         e.stopPropagation();
     });
});

または、イベントを伝播させます。

$(document).ready(function() {
    $("#content").load("content.html");
    $("#content").click(function(e){
        alert(e.target.id); //may return undefined if no id is assigned.
    });
});

作業例: http://jsfiddle.net/5JmsP/

于 2013-06-12T08:57:46.400 に答える