简体   繁体   中英

How can I get the right image src when I do an onclick function using JQuery?

I created a game that when the start button is clicked, it dynamically deletes that div element and creates a new one in order to show the images I want the user to see. MY GOAL IS THAT WHEN THE USER CLICKS ON THE IMAGE it will console log the src of the image it clicked to verify which image was clicked. My code works. My problem is that when I click any of the images, it can't tell the difference between the images sources.

would it be good to put an onclick function inside the if statement? I was thinking...if this source is clicked, then console log it's source.

//startButton onclick function//

$("#startButton").on("click", function (event) {

//when button is clicked, it removes intro-container div and everything inside//

    $(this).closest(".intro-container").remove();

//image sources//

    kevImage = 'src=assets/images/kevin-durant.png';
    lebImage = 'src=assets/images/kobe-bryant.png';
    kobImage = 'src=assets/images/lebron-james.png';
    micImage = 'src=assets/images/michael-jordan.png';

//dynamically creating new elements//

    $("#characterPage").append("<div class= intro-container>" +
        "<h1> CHOOSE YOUR BALLER" + "</h1>" +
        "<div class=image-container>" +
        "<img class = image " + kevImage + ">" + "<img class = image " + lebImage + ">" +
        "<img class = image " + kobImage + ">" + "<img class = image " + micImage + ">" +
        "</div>" +
        "</div>");

//onclick on image class

    $(".image").on("click", function (event) {

//if statement that executes only if kevImage is selected

        if (kevImage) {
            console.log('correct');
        } else {
            console.log('wrong');
        }

    });


});

Picture of my code

尝试$(".image").attr('src')并将结果记录在控制台中。

Replace it with this:

$(".image").on("click", function (event) {

                if ($(".image").attr('src')) {
                    console.log($(this).attr('src'));
                } else {
                    console.log('wrong');
                }

            });

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