jquery - append() 发生在 hide() 之前

标签 jquery

我想隐藏所有子项,然后附加 otherChild。问题是有时append()先发生然后hide()发生(Chrome、Firefox)。

我的期望:

Parent
Other child

但有时会打印:

Parent
Child

实际上,如果我在 IE9 中运行此代码,它总是打印:

Parent
Child

完整代码

<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">

  <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.0.js'></script>

<script type='text/javascript'> 
$(document).ready(function(){
    // Hide children.
    $(".parent").children().hide();

    // Append more child.
    $(".parent").append("<div class=\"otherChild\">Other child</div>");
});
</script>
</head>

<body>
    <div class="parent">
        Parent
        <div class="child">
            Child
        </div>
    </div>
</body>
</html>

最佳答案

<强> Demo Fiddle

通过 hide() 使用回调 - Reference

.hide('持续时间',回调):

  • 第一个参数采用事件的持续时间。如果您想要快速隐藏事件,请在此字段中使用 0
  • 第二个回调,在隐藏事件完成后执行。
<小时/>
$(document).ready(function(){

    $(".parent").children().hide(0, function() {
        $(".parent").append('<div class="otherChild">Other child</div>');
    });
});

关于jquery - append() 发生在 hide() 之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24320000/

相关文章:

javascript - 在javascript中创建动态关联数组

javascript - jQuery 防止默认问题

javascript - jquery not function 没有按预期工作

asp.net-mvc - 如何使用 jquery 或 ajax 更新 MVC 项目的 C#/asp.net 中的 razor 部分 View

jQuery 水平切换 Div

jquery - 查明复选框是否被选中

javascript - 图像 slider 的响应式设计不符合预期

javascript - Jquery val();没有获得值(value)

javascript - 发送问题 -> 加密 -> 使用 jQuery 和 PHP 获取

javascript - 将值从脚本文件传递给 html 中的键