【问题标题】:Run javascript on dynamically loaded content for ajax based website在基于 ajax 的网站的动态加载内容上运行 javascript
【发布时间】:2015-01-04 16:11:15
【问题描述】:

我目前正在设计一个基于 ajax 的导航网站。我遇到的问题是当我尝试在动态加载的内容上运行 jquery 时它不起作用。

这是我所做的:

index.html

<html>
<head>
    <title>Testing Dynamic Content</title>
    <link href="style.css" rel="stylesheet"/>
    <script src="http://localhost/jquery.js"></script>
    <script src="main.js"></script>
</head>
<body>
    <div class="main">
        <div class="content">
            <ul class="list">
                <li>One</li>
                <li>Two</li>
                <li>Three</li>
                <li>Four</li>
            </ul>
        </div>
    </div>
    <script>
    $('.list').greenify();
    </script>
</body>
</html>

2.html

<html>
<head>
    <title>Testing Dynamic Content</title>
    <link href="style.css" rel="stylesheet"/>
    <script src="http://localhost/jquery.js"></script>
    <script src="main.js"></script>
</head>
<body>
    <div class="main">
        <div class="content">
            <span id="hello">Content</span>
        </div>
    </div>
    <script>
    $('#hello').on('click',function(){
        $('.main').load('index.html .content');
        $('.list').greenify();
    });

    </script>
</body>
</html>

style.css

.list{
    color:#f00;
}

ma​​in.js

$.fn.greenify = function() {
    this.css( "color", "red" );
};

问题出在$('list').greenify();。当我使用 .load() 在 2.html 上加载 index.html 的内容时,内容以 css 中定义的红色加载。当我在这个加载的内容上运行 $('list').greenify() 时它不起作用。

我怎样才能运行这个发生在动态加载的内容上运行 JavaScript?

我需要这样做才能在动态加载的网页上运行幻灯片。并且幻灯片无法正常工作。

【问题讨论】:

    标签: javascript jquery html ajax


    【解决方案1】:

    问题是您的代码在您的页面成功加载之前运行,请将您的代码移动到文档就绪事件:

    $(document).ready(function(){
       $('.list').greenify();
    })
    

    并且 jQuery 加载是异步的,你需要在成功函数中运行你的 javascript

    $('.main').load('index.html .content', function() {
        //will execute when load successfully
        $('.list').greenify();
    });
    

    【讨论】:

      【解决方案2】:

      你应该像这样绑定事件,那么只有你的脚本会影响动态 DOM 元素

       $('body').on('click','#hello',function(){
              $('.main').load('index.html .content');
              $('.list').greenify();
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-06
        • 2011-05-12
        • 1970-01-01
        • 1970-01-01
        • 2012-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多