dongzhiman2162 2015-05-26 15:57
浏览 39
已采纳

使用jQuery而不使用document.ready函数[关闭]

I have an ajax function that will get respond from server the respond will contain some buttons, I want to control them with jQuery, but the problem is that they won't exist once the page is opened so I can't control them with $(document).ready(function()

Is there any other way to do this ?

  • 写回答

2条回答 默认 最新

  • douwanc63652 2015-05-26 16:15
    关注

    Have you tried event delegation?

    Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future

    https://learn.jquery.com/events/event-delegation/

    You just need an empty wrapper element where you will render the buttons in the future, after page loads. So, when you add the buttons, you will be able to interact with them.

    At the beginning, the wrapper element must exists in your HTML:

    <div id="buttonsWrapper"></div>
    

    After that, after the ajax call is completed, then you append the buttons from the server to that element:

    <div id="buttonsWrapper">
        <button>From server</buttom>
        <button>From server</buttom>
    </div>
    

    With this JS, you delegate the click event on the wrapper "#buttonsWrapper" element:

    $(function(){
        $("#buttonsWrapper").on( "click", "button", function( event ) {
            event.preventDefault();
            console.log( $( this ).text() );
        });
    }());
    

    With event delegation, it doesn't matter if you add the buttons after page loads. Hope that helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图