jQuery事件不适用于ajax加载的内容 [英] Jquery events not working on ajax loaded content

查看:102
本文介绍了jQuery事件不适用于ajax加载的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码有效。如果有更好的方法,请告诉我。
如果我使用通过ajax加载test.html的主页中test.html中存在的脚本内容。脚本不起作用。

The below code works. If there is some better way please let me know. If i use the script content which is present in test.html in the main page where I am loading test.html through ajax. The script doesn't work.

<html> 
    <head>
        <script src='jquerylocation' type='text/javascript'></script>
    </head>
    <body>
        <div id='ajaxload'></div>
        <button class='test'>load content via ajax</button>
    </body>


    <script>
        $(function(){
            $('.test').on('click',function(){
                  $('#ajaxload').load('test.html');
            });            
        });
    </script>
</html>

Test.html:

Test.html:

    <h1 class='heading'>Page via AJAX</h1>

    <script>
        $(function(){
            $('.heading').on('click',function(){
                $(this).css('color','red');  
            });                          
        });
    </script>

我们必须通过ajax加载脚本以及动态加载的内容,才能按需工作。我感觉是每次我们发送ajax请求脚本时总是将其内容与内容一起加载。但是我只找到了这种解决方案。如果有人知道更好的解决方案,请答复。

we have to load the script along with dynamically loaded content through ajax to work as you require.But disadvantage I felt was each time we send ajax request script loads all the time along with content. But I found only this solution. If anyone knows better solution please reply.

例如,如果以这种方式更改代码将无法正常工作。

For example if change the code this way it wont work.

<html> 
    <head>
        <script src='jquerylocation' type='text/javascript'></script>
    </head>
    <body>
        <div id='ajaxload'></div>
        <button class='test'>load content via ajax</button>
    </body>


    <script>
        $(function(){
            $('.test').on('click',function(){
                  $('#ajaxload').load('test.html');
            });

            $('.heading').on('click',function(){
                $(this).css('color','red');  
            });                                   
        });
    </script>
</html>

Test.html:

Test.html:

    <h1 class='heading'>Page via AJAX</h1>


推荐答案

这是因为您要将事件绑定到准备就绪的文档上。您必须使用委托才能使其正常工作。就像上一样。这是因为.header加载时不在页面上的页面上。因此,没有附加事件。

It's because you are binding the event on document ready. You have to use a delegate in order for this to work. Like on. It's because .header isn't on the page on the page when it's loaded. So no event is attached.

您的代码应与以下内容相似:

Your code should look some along the lines of this:

$('body').on('click','.heading',function(){
     $(this).css('color','red');  
});   

它不必是主体,但是在准备好文档后不会加载的元素,是 .heading 的父级。

It doesn't have to be body, but an element which isn't loaded after document ready, which is a parent of .heading.

这篇关于jQuery事件不适用于ajax加载的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆