繁体   English   中英

jQuery如何单击触发函数?

[英]Jquery how to trigger function if clicked?

我正在尝试创建一个简单的错误消息,该错误消息应在点击页面时消失。

这是我的Jsfiddle: http : //jsfiddle.net/ZKgWR/1/

我想在可见的页面上单击时隐藏.super消息。

这是我的jQuery:

// show super on click
$('.error').click(function(e) {
    e.preventDefault();
    var position = $(this).position();
    $('.super').css({
        display: 'block',
        position: 'absolute',
        left: position.left + 50,
        top: position.top
    });
    var super = true
});


// If .error clicked then enable the function to remove the super message
if ($('.error').show()) {
    $(document).click(function() {
        $('.super').hide();
    });
}


// If .error clicked then enable the function to remove the super message
if ($('.error').show()) {
    $(document).click(function() {
        $('.super').hide();
    });
}

问题是这部分代码无法正常工作:

if ($('.error').show()) {
    $(document).click(function() {
        $('.super').hide();
    });
}

单击.error时,不会附加任何内容,因为在看不到.super时,该功能也处于活动状态。

为什么不添加一个称为active或visible的类?

$('.error').click(function (e) {
e.preventDefault();
var position = $(this).position();
$('.super')
   .show()
  .css({display: 'block', position: 'absolute', left: position.left + 50, top: position.top})
.addClass("active");
});

$(document).click(function() {
   if($('.super').hasClass("active"))
     $('.super').removeClass("active").hide();
});

您的错误是在if语句中,必须执行一个事件才能进行任何检查...

编辑:

看着您的js小提琴,我意识到我犯的错误,应该是e.stopPropogation,下面是完整的工作代码:

$(document).click(function(e) {
    if($('.super').hasClass("active"))
        $('.super').hide();
});

$('.error').click(function(e) {
    e.stopPropagation();
    var position = $(this).position();
    $('.super').fadeIn(250).css({
        display: 'block',
        position: 'absolute',
        left: position.left + 50,
        top: position.top
    }).addClass("active");
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM