简体   繁体   中英

Javascript hide DIV, Button clicked

Hi there Stackers,

I'm back with another problem. It's Javascript (again). I've been creating "alerts" for on my webpage. They contain a button, and I want to close them when I click on a button. However, this doesn't seem to work. I've logged the clicks in the console, and the click is logged. The click does happen.

The Alerts hide after a few seconds. When I change the style with the "Devtools" of Chrome to make it visible again, and click the button then, the DIV does dissapear.

Why does the click not hide my div?

Javascript

var messageId = 0;

    var alerty = function(type, title, content) {
        messageId++;
    var html = ' <div class="alert" id="a-' + messageId + '"><div class="topview ' + type + '"></div><div class="title">' + title +'</div> <div class="text">' + content +'</div> <input type="button" id="close-'+ messageId + '" class="inputbutton-empty ' + type + '2 button close" value="Meldung schlie&szlig;en"></div>'
    $(html).hide().appendTo("#alertcontainer").fadeIn("fast");
    $(".alert").delay(8000).fadeOut();
    $("#close-" + messageId ).click(function() {
        console.log("XTM: Pushed Alerty alert closed on request.");
        $("#a-" + messageId ).hide("fade", "fast");
    });
}

Thanks in advance, Pascal

It is probably the delay() that is preventing your hide() call. Try clearing the queue first in your close function:

$("#close-" + messageId ).click(function() {
        console.log("XTM: Pushed Alerty alert closed on request.");
        $("#a-" + messageId ).stop().hide("fade", "fast");
    });

It's probably because you need to use .on instead of .click.

.on is for newly created DOM elements, which you are doing with your html.

See: jQuery function not binding to newly added dom elements and http://api.jquery.com/on/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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