首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用closest遍历jQuery

使用closest遍历jQuery
EN

Stack Overflow用户
提问于 2011-07-17 06:07:11
回答 2查看 140关注 0票数 1

HTML:

代码语言:javascript
复制
<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

代码语言:javascript
复制
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的函数。我的代码现在可以工作了,但它也会关闭其他元素。做这件事的优雅方式是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-07-17 06:23:18

这应该可以做到:

代码语言:javascript
复制
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 ();
} 

顺便说一句,为了“优雅”,去掉onclick属性!

然后使用以下命令添加单击功能:

代码语言:javascript
复制
$('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 ()内部。

票数 1
EN

Stack Overflow用户

发布于 2011-07-17 06:15:48

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6720562

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档