繁体   English   中英

如何通过jquery选择器选择父元素的子元素?

[英]How to select a child element of parent by jquery selector?

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

<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>

通过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,避免编写内联脚本/样式。

尝试这样的事情

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. 给活动元素一个ID(在这种情况下,我给它click )。

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

     $('#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/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM