2013-12-12 186 views
1

如何选择“tbody”从下面的html代码中的函数“tbodyExpand()”使用jquery? 我试图使用$(this).closest('table').find('tbody')但不起作用。如何通过jquery选择器选择父级的子元素?

<div class="bs-example"> 
    <table class="table table-border table-striped table-condensed table-hover"> 
     <thead> 
     <tr> 
      <td><b>TITLE</b><a href="javascript:void(0)" onclick="tbodyExpand()" style="float: right;">EXPAND</a></td> 
     </tr> 
     </thead> 
     <tbody class="hide"> 
     <tr> 
      <td>ALT (U/L)</td> 
      <td><input class="span1" name="ALT" value="" placeholder=""></td>    
     </tr> 
+0

什么是$(this)引用? –

+0

请参阅此评论:http:// stackoverflow。com/a/9122287/2812842 –

+0

你为什么首先将inline'onclick'与jQuery结合起来?只需使用jQuery http://api.jquery.com/click/ – charlietfl

回答

2

这样做onclick="tbodyExpand.call(this)"你可以使用:

$(this).closest('table').find('tbody'); 

否则this在函数内部将指向全局对象(窗口)不是元素点击。

不用编写内联处理程序,您可以使用选择器绑定事件。

例子:

<a href="#" class="expand floatRight">EXPAND</a> 

CSS:

.floatRight{ 
    float: right; 
} 

$(function(){ 
     $('.expand').click(function(e){ 
      e.preventDefault(); //Much better than doing javascript:void(0) 
      var $tbody = $(this).closest('table').find('tbody');` 
      //or $(this).closest('thead').next('tbody'); 
     }); 
    }); 

这种方式,您也可以分离出来,CSS,JS和HTML和避免编写内嵌脚本/风格。

1

尝试这样的事情

HTML

<a href="javascript:void(0)" onclick="tbodyExpand(this);" style="float: right;">EXPAND</a> 

的JavaScript

function tbodyExpand(obj){ 
    // your other code goes here 
    $(obj).closest('table').find('tbody'); 
    } 
1

虽然所有这些例子中是合法的,你可以大大只需将您的结构:

  1. 给活动元素一个ID(在这种情况下,我给它click)。

  2. 绑定到.click()事件ID的:

    $('#click').click(function(e) { 
        //you can do stuff here! and use $(this). 
    }); 
    
  3. 搜索元素你想要的:

    $(this).closest('table').find('tbody');

结果造成:

<div class="bs-example"> 
    <table class="table table-border table-striped table-condensed table-hover"> 
     <thead> 
      <tr> 
       <td><b>CLICK EXPAND:</b> <a href="#" id='click' style="float: right;">EXPAND</a> 
       </td> 
      </tr> 
     </thead> 
     <tbody class="hide"> 
      <tr> 
       <td>ALT (U/L)</td> 
       <td> 
        <input class="span1" name="ALT" value="" placeholder="" /> 
       </td> 
      </tr> 
     </tbody> 
    </table> 
</div> 

而JavaScript(用jQuery加载):

$('#click').click(function(e) { 
    e.preventDefault(); //blocks the default action of an <a> link. 
    console.log($(this).closest('table').find('tbody')); 
}); 

(请注意,我稍微修改了代码,使其更容易地看到发生了什么)。

在这里玩弄http://jsfiddle.net/remus/VNpn7/