简体   繁体   中英

JQuery .click doesn't work with php file

I have a website which connects to a database and displays some pictures. I want to make it so that when you click one of the pictures, it will display an alert but that doesn't seem to work when the images are dynamically rendered. Whenever i try it on jsbin it works but when i try it with a php file it doesn't. I am using jquery and bootstrap.

JSbin: http://jsbin.com/xamovudiroqe/2/

PHP code

while($i > $y){

    $picture_query =  mysqli_query($link, "SELECT * FROM images WHERE team = '$full_table_array[$y]' AND teamphoto = 1");
    $picture_array = mysqli_fetch_array($picture_query);

    echo "
        <div data-team=\" ".$picture_array['team']." \" class=\"col-xs-6 col-md-3\">
            <a href=\"#\"  class=\"team-nail thumbnail\">
              <img src=\" ".$picture_array['name']." \" >
            </a>
        </div> 

        ";

    $y++;
}

Javascript code

   $(".team-nail").click(function() {
    var team = $(this).attr('data-team');
    alert(team);
    alert("hi");
    console.log(team);
});

I see the problem. You are adding the click event to the anchor element, but the data-team attribute is on the div element. All you need to do is move the data-team attribute the anchor and it will work like a charm.

 echo "<div data-team=\" ".$picture_array['team']." \" class=\"col-xs-6 col-md-3\">
            <a href=\"#\"  class=\"team-nail thumbnail\">
              <img src=\" ".$picture_array['name']." \" >
            </a>
        </div>";

To:

 echo "<div class=\"col-xs-6 col-md-3\">
            <a href=\"#\" data-team=\" ".$picture_array['team']." \" class=\"team-nail thumbnail\">
              <img src=\" ".$picture_array['name']." \" >
            </a>
        </div>";

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