繁体   English   中英

在ajax加载的页面上执行JQuery操作

[英]Perform JQuery actions on ajax loaded page

我正在尝试访问使用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>       

所以我想发生的事情是:当我单击content div中的标签时,它应该显示该标签的ID,即“ header1”,但当前仅显示“ content”。 我该如何实现?

先感谢您

将事件处理程序绑定到内容中的每个元素。

$(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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM