2014-03-25 40 views
0
<script type="text/javascript"> 
    $(function(){ 
    $('#example')[0].onmouseover = function(event) { 
    alert("something"); 
    }; 
    }); 
</script> 

使用jQuery选择DOM

<body> 
<img id="example" src="example.jpg" " alt="ooooh! ahhhh!"/> 
</body 

为什么我们需要[0]背后例如ID?

如果我们删除[0],为什么它不工作?

回答

3

既然你调用本地onmouseover你需要参考本地DOM元素

$('#example')[0] // gives native DOM Element. 

$('#example')[0].onmouseover=function(){}; //native event handling 

如果删除[0]然后你指的jQuery对象。所以,你需要使用事件处理

$('#example') //gives jQuery object 
$('#example').mouseover(function(){}); //jQuery event handling 
0

的jQuery的方式尝试

$(document).on("mouseover","#example",function(event) { 
alert("something"); 
}; 
0

.onmouseover是一个JavaScript事件处理程序,只适用于DOM元素。由于$('#example')是一个jQuery对象,因此onmouseover根本不会做任何事情(甚至不会产生错误)。但是,每个jQuery对象也伪装成一个数组,所以我们可以使用数组解引用操作符通过$('#example')[0]获取底层元素,该元素返回onmouseover(以及任何其他本地JavaScript事件处理程序)可以使用的元素。