javascript - 使用 JQuery 隐藏 div - 不起作用

标签 javascript jquery html

页面加载时会显示一个 div。我在这个 div 中添加了一个按钮,我希望当用户单击这个按钮时,它将使用 JQuery 隐藏该 div。

这是 html:

<div id="tabs" class="news1">
    <ul>
    <li><a href="#tabs-1">Track</a></li>
    <li><a href="#tabs-2">History</a></li>
    </ul>
    <div id="tabs-1">
    <table id="currentloc_table">
    <tr>
    <th></th>
    <th>Name</th>
    <!--th>Latitude</th>
    <th>Longitude</th-->
    <th>Details</th>
    </tr>
            <tr><td></td></tr>
    </table>
    </div>
    <div id="tabs-2">
    </div>

    <button>hide</button>

</div>

这是同一页面上标记中的脚本:

<script>
        $(function() {
            $( "#tabs" ).tabs();
        });

        $("button").click(function() {
            $(this).parent().hide();
        });
</script>

但是由于某种原因它不起作用。有什么建议吗?

谢谢。

最佳答案

您需要将 .click 绑定(bind)放入 $(function () {}) 内。像这样。

    $(function() {
        $( "#tabs" ).tabs();
        $("button").click(function() {
            $(this).parent().hide();
        });
    });

在 jQuery 中,$(function () {}) 是 $(document).ready(function () {}) 的简写,当加载页面的所有 HTML 时调用它。当您将绑定(bind)置于此就绪调用之外时,它会在加载 HTML 之前尝试进行绑定(bind)。如果未加载 HTML,则不存在可绑定(bind)的元素,因此不会应用任何绑定(bind)!通过将其移动到ready(或您的速记ready)内部,我们确保所有元素都已加载并且能够正确绑定(bind)。

关于javascript - 使用 JQuery 隐藏 div - 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15866438/

相关文章:

javascript - 我需要我的 javascript 代码来通过代码块检索 id

javascript - 快速按钮 vs 消除 ios UIWebView 上的触摸延迟?

javascript - 延迟加载不适用于由 leaflet/mapbox 添加的图像

html - 如何使用CSS创建圆 Angular 背景框?

asp.net - JSON 转换中丢失的 xml 数据

javascript - 使用 jquery 1.7 同步 POST

jquery - 使网页横幅响应

javascript - 使用 jquery 从数组中获取唯一数据

javascript - IE innerHTML 改变内容?

html - 在边框内看不到按钮