0

加载时会在页面上显示一个 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>

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

谢谢。

4

2 回答 2

3

您需要将 .click 绑定放在 $(function () {}) 中。像这样。

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

In jQuery $(function () {}) is a shorthand for $(document).ready(function () {}) which is called when all the HTML for the page is loaded. When you put a binding outside of this ready call, it attempts to bind before the HTML is loaded. If the HTML isn't loaded, no elements exist to bind to, so then no bindings are applied! By moving it inside of the ready (or your short-hand ready), we ensure that all elements are loaded and capable of being bound to properly.

于 2013-04-07T18:56:34.973 回答
2

You just need to put your code below:

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

Inside the $(function() {} like:

$(function () {

    // Call the jQuery tabs
    $("#tabs").tabs();

    // Call button click event here
    $("button").click(function () {
        $(this).parent().hide();
    });
});

This would specify the click event to execute when the DOM is fully loaded.

于 2013-04-07T19:02:54.980 回答