0

在我的项目中,您可以单击一个地区,它的县徽出现在底部。

我的项目

我有一些 jquery 悬停在新添加的波峰上,我想在他们的类上使用选择器。每个波峰都添加了:

$("#selectResult").append("<div id='"+arr[this.id]+"' class='inline'></div>");
var addThis = arr[this.id];
$("#" + addThis).css({'background-image' : 'url(./coatofarms/'+arr[this.id]+'.png)',
'background-repeat': 'no-repeat',
'background-position': 'bottom'});

我的 jquery 测试悬停是:

 $(".inline").hover(function(){
         alert('in');
}, function(){
         alert('out');
});

该类是 .inline ,但选择不起作用(?)在 div ID 上测试,它工作得很好。有人可以告诉我哪里出错了吗?蒂亚

4

3 回答 3

2

由于您.inline动态附加到 DOM,因此普通绑定在这里不起作用。您需要委托事件处理程序来执行如下操作:

$('#selectResult').on('hover', '.inline', function(e) {
   if(e.type == "mouseenter") {
      alert('In');
   } else {
      alert('Out');
   }
});

.on()委托事件处理程序的方法需要使用如下:

$(container).on(eventName, target, handlerFunction);

这里,container指向的元素是静态元素,即在页面加载时属于 DOM,而不是动态附加。尽量避免documentbody作为container参考。

于 2012-06-07T18:16:08.043 回答
1

如果您要动态添加元素,则需要设置一个委托,以便在这种情况下为给定元素订阅一个或多个事件。

使用 jQuery on()

就像是:

$(document).on('mouseover mouseout', '.inline', function(e){
      if(e.type == 'mouseover')
      {
         alert('in');
      }
      else if(e.type == 'mouseout')
      {
          alert('out');
      }
});
于 2012-06-07T18:07:25.103 回答
0

试试这个 :

$(".inline").live("mouseenter",function(){
         alert('in');
}).live("mouseleave", function(){
         alert('out');
});
于 2012-06-07T18:21:14.730 回答