【问题标题】:.click function not working on code loaded using Ajax.click 函数不适用于使用 Ajax 加载的代码
【发布时间】:2013-02-18 16:11:34
【问题描述】:

使用 Ajax 将以下 HTML 加载到 HTML 页面的 div 中,我想在用户单击该 HTML 中的 a.start-btn 时执行代码,由于某种原因它没有检测到那里的点击,我'我试过 .live 但没有用。有什么问题?谢谢

<div class="map">
    <div class="game-step1">
        <div class="note">
            <h5>Day 5</h5>
            <p>Today is the 5th day of our trip around the world... We have already visited Rome, Istambul, Kenya and Maldives.<br/><br/>
<strong>Ready to guess what will be our next destination?</strong></p>
         </div>
         <img src="img/route1.png"  class="route route1"/>
         <a href="#" class="game-button start-btn" >Start the Game &raquo;</a>   
     </div>
</div>




 function showReadyMsg() {
            $('.game-step1').animate({left:'-886px'}, 500);
            console.log('showReadyMsg called')
        }

        $(".start-btn").live("click", function(){
            console.log('button clicked')
            showReadyMsg();
        });

【问题讨论】:

标签: jquery ajax live


【解决方案1】:

Live 在早于 jQuery1.9 的版本中已被弃用,并在 jQuery 1.9 中被删除。使用 .start-button 对任何动态创建的元素在委托上使用文档

试试这个

$(document).on('click','.start-btn',function(){
     //Code here
});

【讨论】:

    【解决方案2】:

    对通过 AJAX 加载的项目进行的任何 JavaScript / jQuery 操作都需要在回调函数中设置,否则将看不到。

    $('#LoadingDiv').load('some.php #file',function(){
        // javascript to be done on the #file stuff you loaded
    });
    

    这是一个过于笼统的例子。如果你没有任何参数要传递给回调函数,你甚至可以只使用你已经创建的函数的名称而不是显式声明。

    $('#LoadingDiv').load('some.php #file',jsFunctionToCall);
    

    两者都应该工作。

    【讨论】:

      猜你喜欢
      • 2011-05-16
      • 1970-01-01
      • 2014-09-04
      • 1970-01-01
      • 1970-01-01
      • 2013-12-05
      • 1970-01-01
      • 2013-06-22
      • 2018-03-05
      相关资源
      最近更新 更多