简体   繁体   English

使用JQuery执行onclick函数时,如何获得正确的图像src?

[英]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. 我创建了一个游戏,单击“开始”按钮时,它会动态删除该div元素并创建一个新元素,以显示我希望用户看到的图像。 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. 我的目标是,当用户单击图像时 ,它将控制台记录其单击的图像的src,以验证单击的图像。 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? 将onclick函数放在if语句内会好吗? 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');
                }

            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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