javascript - $(this).find 不工作

标签 javascript jquery html css

我试图在单击 tr 时显示/隐藏某些内容,但不知何故无法正常工作。这是简化的代码:

HTML:

<table>
    <tr onclick="showDetails()">
        <td>Some text
            <br> <span class="hiddenContent">Some hidden content</span>

        </td>
        <td>Some More Text
            <br> <span class="hiddenContent">Some hidden content</span>

        </td>
    </tr>
    <tr onclick="showDetails()">
        <td>Some text
            <br> <span class="hiddenContent">Some hidden content</span>

        </td>
        <td>Some More Text
            <br> <span class="hiddenContent">Some hidden content</span>

        </td>
    </tr>
</table>

JavaScript:

function showDetails() {
    $(".hiddenContent").hide();

    $(this).find(".hiddenContent").show();
}

最佳答案

因为this引用了window对象。

如果您希望this 绑定(bind)到被点击的元素,您可以使用.call() method 调用该函数。并传递 this

Example Here

<tr onclick="showDetails.call(this)"></tr>

或者,您也可以将对 this 的引用作为参数传递:

Example Here

<tr onclick="showDetails(this)"></tr>
function showDetails(el) {
    $(".hiddenContent").hide();

    $(el).find(".hiddenContent").show();
}

更好的方法是使用 unobtrusive JavaScript并将事件监听器附加到 tr 元素:

Example Here

$('tr').on('click', function () {
    $(".hiddenContent").hide();
    $(this).find(".hiddenContent").show();
});

关于javascript - $(this).find 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29132659/

相关文章:

JavaScript 正则表达式验证

javascript - 尼尔利。如何解析语法 近用JS语法

jquery - 使用 touchstart 关闭 iphone/ipad 上的 jQuery Tools 工具提示

javascript - HTML 不调用 javascript 函数

html - chrome 布局仅在窗口调整大小后正确

javascript - 如何在 javascript 中定义文档?网络 Storm

javascript - 打开和关闭 fancybox 时更改 url

javascript - 如何在循环中使用 selection.filter 方法将 D3 选择分组

javascript - 滑动事件未触发

javascript - 相当于 :eq 的 Css