点击Jquery检查,否则执行此操作

时间:2014-02-28 02:08:41

标签: jquery

为什么忽略点击并转到else语句?任何帮助表示赞赏!

<div id="boxauto"> <a id="boxclose">X</a> error </div>

<script>
    window.setTimeout(function(){
        $('#boxauto').delay(50).animate({'top':'0'},200); 

        var hasBeenClicked = false;
        jQuery('#boxclose').click(function(){
           hasBeenClicked = true;
        });
        if(hasBeenClicked) {
            $('#boxauto').animate({'top':'-50em'},500);
        } else {
            $('#boxauto').delay(5000).animate({'top':'-50em'},500);
        }
    });
</script>

2 个答案:

答案 0 :(得分:1)

您正在分配单击侦听器并在完全相同的时间检查结果,因此两个代码块都会立即执行。

因此,

hasBeenClicked将始终为false,因为在调用if语句之前无法单击您的链接。


阅读完您的评论后,这就是您所需要的:

var hasBeenClicked = false;

// do this as soon as the doc is ready
$(document).ready(function() {

    // move your box into it's intial position
    $('#boxauto').delay(50).animate({'top':'0'},200);

    // listen for the click
    jQuery('#boxclose').click(function() {
        // on click, set the flag and move the box
        hasBeenClicked = true;
        $('#boxauto').animate({'top':'-50em'},500);
    });

});

// after five seconds, move the box if it wasn't moved already
window.setTimeout(function(){
    if (!hasBeenClicked) {
        $('#boxauto').animate({'top':'-50em'},500);
    }
}, 5000);

答案 1 :(得分:0)

您正在超时中绑定处理程序。用户永远没有机会点击按钮。这样做:

<div id="boxauto"> <a id="boxclose" href="#">X</a> error </div>

<script>
var hasBeenClicked = false;

jQuery('#boxclose').click(function(e){
   hasBeenClicked = true;
   e.preventDefault();
});

window.setTimeout(function(){
    $('#boxauto').delay(50).animate({'top':'0'},200); 

    if(hasBeenClicked) {
        $('#boxauto').animate({'top':'-50em'},500);
    } else {
        $('#boxauto').delay(5000).animate({'top':'-50em'},500);
    }
});
</script>

注意,您实际上并没有给setTimeout电话留出时间。我认为默认值类似于400ms。我怀疑用户能够快速点击按钮。

我还注意到您没有<a>的参考资料。你需要给它一个href='#'所以它知道不去任何地方。并使用e.preventDefault()来阻止链接实际导航。