简体   繁体   中英

jquery click-function is executed when page loads but not when clicked

I use jQuery to get the height of a div #img-copyright when the page is loaded, write in the var copyrightHeight and set the height of the div to 0.

When a different div is clicked, the function showImgCopyright() should set the max-height of the div #img-copyright to the content of the var.

I made two tries.

First one:

var copyrightHeight;

$(document).ready(function () {

    copyrightHeight = $("#img-copyright").height();

    console.log(copyrightHeight);
    // just used to see if the height got written in the var - it is

    $("img-copyright").css("max-height", 0);

    $("#show-img-copyright").click(showImgCopyright());

    function showImgCopyright() {
        $("#img-copyright").css("max-height", copyrightHeight);
    }


});

Second one:

var copyrightHeight;

$(document).ready(function () {

    copyrightHeight = $("#img-copyright").height();

    console.log(copyrightHeight);
    // just used to see if the height got written in the var - it is

    $("img-copyright").css("max-height", 0);

    $("#show-img-copyright").click(function (){
        $("#img-copyright").css("max-height", copyrightHeight);
    });


});

In the first example the function is directly executed after the page is loaded and NOT when clicking the div (not the way I wanted it to be). In the second example it works as I wanted it - the function just is executed when clicking the div. But I don't get why.

How can I make it work with an extra function like in the first example?

Thank you very much.

I also found out, I forgot a # in the line $("img-copyright").css("max-height", 0); .

So the right code would be:

var copyrightHeight;

$(document).ready(function () {

    copyrightHeight = $("#img-copyright").height();

    $("#img-copyright").css("max-height", 0);

    $("#show-img-copyright").click(showImgCopyright);

    function showImgCopyright() {
        $("#img-copyright").css("max-height", copyrightHeight);
    }

});

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