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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度