简体   繁体   中英

jquery code not executing from script, but executing from dev panel

http://www.henrybuilt.com/trade2/resource.php?id=100

Check out the link above. Login: asdf, asdf

EDIT: Click on bamboo on the link above once you've logged in. Thanks.

The following code (which toggles a 'popup' window (div)) won't execute on the page, but will work when copied and pasted in the dev panel.

            $(".maintypedata img").click(function() {
                console.log("test");
                if(open == false) {
                    var src = $(this).attr("src");
                    $(".popup").html("<img src='"+src+"'/>");
                    open = true;
                    $(this).addClass("selected");
                    $(".popup").slideFadeToggle(function() { 

                    });
                }
            });

How can I make it run from the script?

The click handler you've shown is bound to any ".maintypedata img" elements that exist when that code runs. But, the img elements in question are appended to the document dynamically after the "Bamboo" option is clicked. So you need to either run that .click() code after the elements are appended (which is what you were doing by running it from the console) or change it to work as a delegated event handler:

        $(".maintypedata").on("click", "img", function() {
            console.log("test");
            if(open == false) {
                var src = $(this).attr("src");
                $(".popup").html("<img src='"+src+"'/>");
                open = true;
                $(this).addClass("selected");
                $(".popup").slideFadeToggle(function() { 

                });
            }
        });

That is, bind the click handler to an element that exists initially, in this case ".maintypedata" , but specify a selector in the second parameter to .on() and jQuery will only run your handler if the clicked item matches that second select at the time of the event.

(A delegated handler is also more efficient than binding the same handler to lots of separate elements, but that's just an added bonus.)

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