在我的元素中,您可以单击一个区域,它的县徽出现在底部。
我有一些 jquery 悬停在新添加的波峰上,我想在他们的类(class)上使用选择器。每个波峰都添加了:
$("#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 上测试,它完美地工作。 有人可以告诉我哪里出错了吗? 蒂亚
最佳答案
由于您 .inline
动态附加到 DOM,因此普通绑定(bind)在这里不起作用。您需要委托(delegate)事件处理程序来执行如下操作:
$('#selectResult').on('hover', '.inline', function(e) {
if(e.type == "mouseenter") {
alert('In');
} else {
alert('Out');
}
});
.on()
委托(delegate)事件处理程序的方法需要使用如下:
$(container).on(eventName, target, handlerFunction);
这里,container
指向的元素是静态元素,即在页面加载时属于 DOM,而不是动态追加。尽量避免将 document
或 body
作为 container
引用。
关于jquery - css 类选择器不工作,不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10937273/