简体   繁体   English

jQuery如何单击触发函数?

[英]Jquery how to trigger function if clicked?

I am trying to create a simple error message that should disapear on page click. 我正在尝试创建一个简单的错误消息,该错误消息应在点击页面时消失。

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

I want to hide the .super message when clicked on the page, when the message is visable. 我想在可见的页面上单击时隐藏.super消息。

Here is my jquery: 这是我的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();
    });
}

The problem is that this part of the code is not working: 问题是这部分代码无法正常工作:

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

Nothing appends when clicking on .error because of the function is also active when the .super is invisable. 单击.error时,不会附加任何内容,因为在看不到.super时,该功能也处于活动状态。

Why not add a class called active or visible? 为什么不添加一个称为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();
});

Your error was in the if statement, an event must occur first before doing any checks... 您的错误是在if语句中,必须执行一个事件才能进行任何检查...

EDIT: 编辑:

Looking at your js fiddle I realised the mistake I made, it should be e.stopPropogation, here is a full working code: 看着您的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