【问题标题】:jQuery traversing using closest使用最近的jQuery遍历
【发布时间】:2011-07-17 07:54:02
【问题描述】:

HTML:

<table border="1px">
        <tr>
            <td colspan="2">
                <div class="commentLink">
                    <a onclick="ShowBox.call(this); return false;" href="#">Comment</a>
                </div>
            </td>
        </tr>
        <tr class="commentBox" style="display: none;">
            <td colspan="2">
                <div class="hiddenComment">
                    <textarea class="textComment" rows="2" cols="100"></textarea>
                    <input class="foo" type="checkbox" />
                    <input class="commentBtn" type="button" value="Submit" onclick="addComment.call(this); return false;" />
                    <input class="commentBtn" type="button" value="Cancel" onclick="HideBox.call(this); return false;" />
                </div>
            </td>
        </tr>
    </table>

JS:使用 jquery 1.4.2

function ShowBox() {
        var that = this;
        $(function () {
            $(".commentBox").show();
            //$(that).closest('tr').siblings().show();
        });
    }
    function HideBox() {
        var that = this;
        $(function () {
            $(that).siblings(".foo").attr("checked", false);
            $(that).siblings(".textComment").empty();
            $(".commentBox").hide();
        });
    }  

我有两个函数来显示/隐藏一个 tr。我现在拥有的代码可以工作,但它也会关闭其他元素。这样做的优雅方式是什么?

【问题讨论】:

  • 那你为什么不使用closest?在函数内部将函数传递给document.ready 是不必要的。

标签: jquery jquery-selectors jquery-traversing


【解决方案1】:

应该这样做:

function ShowBox() {
    $(this).closest ('tr').next ('tr.commentBox').show ();
}

function HideBox() {
    var jThis   = $(this);

    jThis.siblings(".foo").attr("checked", false);
    jThis.siblings(".textComment").empty ();
    jThis.closest ('tr.commentBox').hide ();
} 


顺便说一句,对于“优雅”,请从 HTML 中删除 onclick 属性!

然后添加点击功能:

$('td div.commentLink > a').bind ('click', ShowBox, false);
$('td div.hiddenComment > a.commentBtn[value=Submit]').bind ('click', addComment, false);
$('td div.hiddenComment > a.commentBtn[value=Cancel]').bind ('click', HideBox, false);

$(document).ready ()内。

【讨论】:

    【解决方案2】:

    closest 选择器是在 1.3 版中添加的,我相信,所以就使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-23
      • 2013-07-06
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多