2014-05-24 170 views
-2

我想通过点击链接来隐藏span标签,但不工作。JQuery隐藏功能不起作用

我使用下面的代码

<script type="text/javascript"> 
    function showhide(obj) { 
     $(obj).closest('tr').find('td span').hide(); 
     //$('.testspan').css('background-color', 'red');  } 
    } 
</script> 

<table> 
    <tr> 
     <td style="padding-top: 16px float:left;" colspan="3" id="asd"> 
      <h3> 
       <u> 
        <a class="faculty_more_des" href='javascript:showhide(this);'>Read More</a> 
       </u> 
      </h3> 
      <span class="testspan">This is test sample </span> 
     </td> 

    </tr> 
</table> 

回答

3

的问题是在href处理this指的是window对象,所以用点击数处理程序来调用该方法

<a class="faculty_more_des" href="#" onclick='javascript:showhide(this);'>Read More</a> 

演示:Fiddle

但我更喜欢使用jQuery来注册事件处理程序,而不是使用内联处理程序

+2

,或者甚至更好,不要使用内联JS事件处理程序在所有,但绑定到链接与jQuery。另外,'javascript:'部分在onclick属性中是不必要的。 – JJJ

+0

谢谢!工作中 –

1

this在你的代码是指window对象,您正在加载jQuery的,使用它的功能:

$('.faculty_more_des').on('click', function(event) { 
    // event.preventDefault(); 
    $(this).closest('h3').next('.testspan').toggle(); 
});