[英]Does $.addClass not update the DOM immediately?
Consider the following snippet.考虑以下片段。
function foo(event) {
var $item = $(event.target);
$item.addClass("className");
bar(event);
};
function bar(event) {
var $item = $(event.target);
// The following return false
if ($item.hasClass("className")) {
// flow of control does not enter
}
};
I am not asking how to get around this.我不是在问如何解决这个问题。 That would be plain obvious: to pass the reference to the $item
to the bar
function.这很明显:将$item
的引用传递给bar
函数。
I am asking if jQuery:我在问 jQuery 是否:
Does or does not update the DOM immediately?是否立即更新 DOM?
When does it update?什么时候更新?
How can I make it update explicitly?我怎样才能让它显式更新?
Finally, where can I read about this?最后,我在哪里可以阅读有关此内容的信息?
Yes.是的。 Immediately.立即地。
The property/attribute of the DOM is updated immediately, you can read the changed value immediately. DOM 的属性/属性会立即更新,您可以立即读取更改的值。 But the UI rendering may delay to the end of the JavaScript code (UI rendering doesn't matter).但是 UI 渲染可能会延迟到 JavaScript 代码的末尾(UI 渲染无关紧要)。
You don't need to.你不需要。
Well ... I think the DOM/ES standards may contain these contents.嗯...我认为DOM/ES标准可能包含这些内容。
And you can think about the "correct behavior" of a design: who can bear the strange behavior that can not read the changed value immediately?而你可以思考一个设计的“正确行为”:谁能忍受不能立即读取改变值的奇怪行为? It must be crazy.一定是疯了。 So your browser always do the right things.所以你的浏览器总是做正确的事情。 :D :D
function foo(event) { var $item = $(event.target); $item.addClass("className"); bar(event); }; function bar(event) { var $item = $(event.target); if ($item.hasClass("className")) { $("#output").text("className changed!") } }; $(function(){ $("#test").on("click", foo); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="test">click me</button> <div id="output">hello</div>
your code should perform as expected, there's no apparent problem with it, but here's the thing that might be creating problems您的代码应该按预期执行,它没有明显的问题,但这里可能会产生问题
when you do addClass, it triggers an even that updates the class='' attribute and removes your className, which is why the condition当您执行 addClass 时,它会触发更新 class='' 属性并删除您的 className 的偶数,这就是条件
($item.hasClass("className"))
returns false返回假
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.