2013-02-18 36 views
0

下面的HTML使用Ajax加载到HTML页面的div中,我想在用户单击该HTML内的a.start-btn时执行代码,因为它没有检测到那里的点击,我试过.live,它没有工作。什么可能是错的?谢谢.click函数不适用于使用Ajax加载的代码

<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(); 
     }); 
+1

[在jQuery中,如何将事件附加到动态html元素?](http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html -elements) – loganfsmyth 2013-02-18 16:15:29

+0

[jQuery on not working]的可能重复(http://stackoverflow.com/questions/8614981/jquery-on-not-working) – 2013-02-18 16:15:54

+0

问题是,他没有将任何函数绑定到通过AJAX加载的项目,除非你在回调函数中明确指出,否则它不会被DOM看到。我在下面的答案中详细说明。 – PlantTheIdea 2013-02-18 16:18:23

回答

1

Live在jQuery1.9之前的版本中已弃用,并在jQuery 1.9中删除。使用上委托与。开始按钮的任何动态创建的元素文件

尽量通过AJAX加载的项目做到了这一点

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

任何的JavaScript/jQuery的操作需要一个回调函数来进行设置,否则它不会被看到。

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

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

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

要么应该工作。

相关问题