2012-09-06 31 views
1

我在做一个AJAX调用服务器页面并通过HTML方法在一个div打印结果:jQuery的.HTML导致

$(document).ready(function() 
{ 
    $.ajax 
    ({ 
    async:false, 
    type: 'GET', cache: false, 
    url: '..urlhere..', 
     success: function(data){printresult(data);} 
     }); 
}); 

与printresult(数据):

$("thediv").html(data); 

这一切都可以工作,但结果本身包含类的跨度。这些跨度在他们徘徊时应该发出简单的警报。我实现了太在的document.ready:

$(".spanclass").hover(function() 
{ 
    alert('j'); 
}); 

这不工作..难道是因为结果来自Ajax和DOM不会看到它作为一个spanclass?

回答

1

您应该使用delegate

$('thediv').delegate('hover', '.spanclass', function() { ... }); 

这是jQuery的

Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. 
+0

尝试将代码放入'$(document).ready()' –

+0

抱歉,这是另一个错误。它现在的作品:) – PoeHaH

+0

很高兴知道它的作品:) –

1

建立一个delegate这样的动态添加元素

$(function(){ 
    // on document ready setup the delegate for the hover event 
    $(document).on('hover', '.spanclass', function(){ 
     alert('j'); 
    }); 
}); 
+0

其描述,当我有增加吗?在我的ajax呼叫的接入? – PoeHaH

+0

您可以将其添加到您的就绪区块中。更新了我的答案。 – Gabe

2

你应该委托的情况下,你可以使用on方法。

$(document).on({ 
    mouseenter: function(){ 
    alert('entered') 
    }, 
    mouseleave: function(){ 
    alert('left') 
    }  
}, ".spanclass") 
0
$('.spanclass').live('mouseover', function() { 
    alert('j'); 
}); 
+1

live已弃用:http://api.jquery.com/live/ –

+0

@ClydeLobo将'hover'作为'on'方法的事件也被弃用。 – undefined

+0

我不认为这是过时的,如果我点击链接 – PoeHaH