2014-05-24 25 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(); 
});