2010-07-01 24 views
0

我有一个jQuery的问题:点击“li”函数,各种ie版本的行为不同..这里是html代码。jQuery:在“李”onclick问题

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 
<script type="text/javascript" src="jquery-1.4.2.min.js"></script> 

<style> 
html,body{ 
font: 90% arial, tahoma, verdana #333 normal; 
margin:0; 
padding:0; 
} 
#treeDiv 
{ 
width:250px; 
background-color:#C4E4EE; 
border:#6BB8DC solid 1px; 
margin:10px; 
} 
ul#jQtree{ 
list-style-type:none; 
margin:10px; 
padding:0; 
background-color:#fff; 
} 
ul#jQtree li 
{ 
padding:5px 10px 5px; 
border:#CCC solid 1px; 
} 
ul#jQtree li label 
{ 
background-color:#666; 
color:#fff; 
} 

</style> 

<script type="text/javascript"> 

$(document).ready(function(){ 
    //on mouseover of li, change cursor to hand 
    $('#jQtree li').hover(function(){ $(this).css({'cursor':'hand'})}); 

    //on click of li, if there are subnodes for it, hide it. 
    $('#jQtree li').click(function(event){ 
    if(event.target.nodeName == "LI" && $(event.target).children('ul').length > 0){ 
    $(this).children('ul').slideToggle("200"); 
    } 
    }); 

}); 

</script> 
</head> 

<body> 
<div id="treeDiv"> 
<ul id="jQtree"> 
<li> 
    <label>Main Node</label> 
     <ul> 
     <li><label>Sub Node 1</label></li> 
      <li><label>Sub Node 2</label></li> 
      <li><label>Sub Node 3</label></li> 
      <li><label>Sub Node 4</label></li> 
     </ul> 
    </li> 
</ul> 
</div> 
</body> 
</html> 

我已经写了jQuery的onclick函数只有“李”有孩子的“UL”。 它在ie8中工作,即使在ie7中,但区别在于,“LI”内部的onclick仅在ie8中工作,而在ie7中,外部“LI”边缘的onclick也工作于。最后在ie6中,光标闪烁,有时变成手,然后我们要点击,否则它不会工作。任何人都可以帮我修复所有版本这个问题。任何黑客?有人请指引我,使工作..

回答

0

你能有这样的点击方法颇多更具可读性:

$('#jQtree li').click(function(ev) { 
    if (this.children('ul').length > 0) { 
     this.children('ul').slideToggle(200); // note that I changed the type 
    } 
} 

此外,.hover()需要函数作为参数 - 一个用于鼠标悬停,和一个为mouseout。如果你什么都不想要发生的鼠标移开时很可能需要添加一个空的功能,但最有可能你想做的事是这样的:

$('#jQtree li').hover(
    function() { this.css('cursor':'pointer'); }, 
    function() { this.css('cursor':'default'); } 
); 

作为一个侧面说明,你已经提供了将执行上两个悬停处理程序进入和退出,这将始终保持光标作为指针。

+0

非常感谢Tomas, ie6的另外一个小问题,我可以点击ie6以外的所有其他浏览器中的'li'标签,在ie6中点击即使'li'填充10px,标签在'li'里面。如果您在ie6中看到我的代码,您将无法获得折叠效果,请停用所有浏览器,然后单击“li”,并且“li”的所有子元素都将通过“slideToggle”功能折叠。你能为这个问题建议任何解决方案.. – DilipKP 2010-07-13 12:47:13