我想隐藏所有子项,然后附加 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/