【问题标题】:Fastest way to access a class after $(this)$(this) 之后访问类的最快方法
【发布时间】:2023-03-30 05:50:02
【问题描述】:

具有以下html结构:

<tr class="invisible">
    <td align="center">
        <a class="i_edit" data-target="30"></a>
    </td>
    <td class="category">
        <span class="f_type" style="background-image: url(/admin/assets/img/f_type_3.gif);"> Tests </span>
    </td>
    <td style="background-color: blue;">
        <select class="behaviour" name="behaviour" style="opacity: 1;">
            <option selected="" value="1" style="opacity: 1;">Por noticias destacadas</option>
            <option value="2" style="opacity: 1;">Por fecha</option>
        </select>
    </td>
</tr>

在里面访问 .i_edit 类的最佳/最快方法是:

$('.behaviour').change(function(){

        $(this).closest('.i_edit').css('background-color', 'red'); //doesn't work
        $(this).parent().closest('.i_edit').css('background-color', 'red'); //doesn't work
        $(this).parent().parent().find('.i_edit').css('background-color', 'red'); //this works

    return false;

});

【问题讨论】:

  • 好吧,如果前两个不起作用,我会说第三个是最好的。

标签: javascript jquery parent closest


【解决方案1】:

三个都不是。

使用$(this).closest('tr').find('.i_edit'),因为它是可读的,并且在你的 DOM 结构发生变化时仍然有效。

另请参阅:http://api.jquery.com/closest/

【讨论】:

  • @Radu &lt;tr&gt; 元素在不包含在表中时被删除:jsfiddle.net/veVqH/3
  • 我没有想到这一点,尽管它确实有道理!感谢您的提示。
  • 实际上,现在我想得更多,我希望 tr 元素将被包装在一个表格中而不是被丢弃.. 只是基于许多浏览器如何自动关闭未关闭的标签。
【解决方案2】:

首先,做一个 .parents('tr.invisible) 然后做一个 .find('.i_edit')

$('.behaviour').change(function(){
    var obj_this = $(this)

    obj_this.parents('tr.invisible').find('.i_edit').css('background-color', 'red');

   return false;
});

如果您需要多次使用它,也可以将 $(this) 保存到变量中。

var obj_this = $(this)

【讨论】:

    猜你喜欢
    • 2019-11-19
    • 1970-01-01
    • 2015-05-25
    • 2012-01-19
    • 2015-08-07
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多