如何在Ajax调用的元素上注册mouserover

How to Register mouserover on elements from Ajax call

本文关键字:元素 注册 mouserover 调用 Ajax      更新时间:2024-06-18

我正试图在用户单击按钮后生成的元素上注册mouseover事件。

这些元素是通过ajax生成的。mouserover似乎无法处理ajax创建的元素。我想知道是否有办法解决这个问题。非常感谢。

jQuery.ajax({
        type: "GET", 
        url: "http://list.php", 
        data: null, 
        dataType:"json", 
              timeout: 10000,
              global: true,
              error: oh_no,
        success: 
     });
var image = document.getElementById('image');
the image path are from ajax.
function listem(){
 ......codes
 ......codes
 image.innerHTML=  image.innerHTML + "<img src="'" + imagePath + '"'>";
} 
$(document).ready(function(){   

   $('#image img').mouseover(function(){
       alert('mouseOVER!!!');
   });
})


html    
<button id='showstuff' onclick='listem();'>show</button>

您还在页面加载中应用侦听器,但此时对象不存在。尝试创建一个类似"AddImageListeners()"的函数,并在ajax调用的"成功"部分调用它。

尝试使用委派(使用.on方法)。您可以将事件处理委托给父对象:

 $('#image').on('click', 'img', function() {});

您不能将鼠标悬停应用于尚不存在的元素,因此您的ready函数将仅应用于现有的#image。做一个关于ajax成功的函数来应用监听器,你应该很好。

jQuery.ajax({
        type: "GET", 
        url: "http://list.php", 
        data: null, 
        dataType:"json", 
              timeout: 10000,
              global: true,
              error: oh_no,
        success: function(){
           $('#image img').mouseover(function(){
               alert('mouseOVER!!!');
           });
        }
     });

您需要根据jQ版本使用live、delegate或on,而不是将鼠标悬停在选择器上。

这意味着还应该将事件触发器添加到动态添加的内容(如ajax调用)中。

要做到这一点,请使用类似的东西。

$(document).ready(
  $("html").on("mouseover","yourselector", yourOnMouseFunction())
);

祝你好运(如果你只想在某些选择器中使用实时事件,html可以被任何父选择器取代)。

您需要在通过ajax创建的元素中注入jquery。这将通过.live()函数、.on()函数或livequery插件来完成。请参阅.live() api.jquery.com/live和livequery docs.jquery.com/Plugins/livequery 的链接