所有,我知道 javascript 在单线程模式下运行。但我不确定在某些情况下是否存在多线程世界中常见的种族问题。假设你有 html 结构
<div id='parent' class="parent container">
<div id="child1" class="child container">
<div id="child11" class="child container">
<!--maybe there are more nested divs with class 'container' -->
</div>
<div id="child12" class="child container">
<!--maybe there are more nested divs with class 'container' -->
</div>
</div>
<div id="child2" class="child container">
<div id="child21" class="child container">
<!--maybe there are more nested divs with class 'container' -->
</div>
<div id="child122" class="child container">
<!--maybe there are more nested divs with class 'container' -->
</div>
</div>
</div>
JS代码:
$(function() {
$('div.container').mouseenter(function(e){
e.stopPropagation();
$(this).css("border","2px solid red");//set it selected state.
$(this).append("<div class='newdiv'></div>");
$(this).parents().each(function(){
if ($(this).children(".newdiv").length>0)
{
$(this).children(".newdiv").remove();
$(this).css("border","1px solid black");//set father of it not selected state
}
});
}).mouseleave( function(e){
$(".newdiv",this).remove();
if ($(this).parent().hasClass("container") && $(".newdiv",$(this).parent()).length==0)
{
$(this).parent().css("border","2px solid red");//set it's parent selected state.
$(this).parent().append("<div class='newdiv'></div>");
}
$(this).css("border","1px solid black");//set it not selected state.
});
});
如果我将鼠标移入和移出这些 div 足够快,我怀疑是否存在种族问题。因为我发现有时div.newdiv
没有被删除。我想我只是不了解javascript的运行机制。所以我有这样一个问题。希望有人愿意告诉我更多关于它的信息,以帮助我更好地理解它。谢谢。