简体   繁体   中英

jquery triggers dont work after dynamically loading new content

I'm making a vote system thats using images and whenever you click one of the images, it will submit that one, and then it fades out and reloads it using a php page. Problem is, the first submit works, but once it reloads, clicking on the images does nothing. Not even an alert which I've tested.

vote.js

$('.firstDisplay').on("click", function () {
    alert("work1");
    var win = $(this).attr("title");
    var loss = $('.secondDisplay').attr("title");
    send_vote(win, loss);
    console.log("<-CLIENT-> Click: Sent vote");
});
$('.secondDisplay').on("click", function () {
    alert("work2");
    var win = $(this).attr("title");
    var loss = $('.firstDisplay').attr("title");
    send_vote(win, loss);
    console.log("<-CLIENT-> Click: Sent vote");
});

function send_vote(win, lose) {
    var data = {'win': win, 'lose': lose};
    $.ajax({
        type: "POST",
        url: 'actions/send-vote.php',
        data: data,
        success: function (html) {
            $('#sent-vote').css('display', 'block');
            $('#sent-vote').fadeOut(2000);
            $('.imageBtn').fadeOut(2000);
            $('#imageDisplay').load("source/templates/vote.php");
            console.log("<-SYSTEM-> Ajax request sent and processed.");
        },
        error: function(e) {
            $('#fail-vote').css('display', 'block');
            $('#fail-vote').fadeOut(2000);
            console.log("<-SYSTEM-> Ajax request failed to process.");
        }
    });
}

vote.php

<?php
$maximumPersons = 95;
$firstDisplay = rand(1, $maximumPersons);
$secondDisplay = rand(1, $maximumPersons);

function getScore($photo_id) {
    $query = "SELECT *
                  FROM photo_scores
                  WHERE photo_id='".$photo_id."'";
    $result = $database->query_select($query);
    return $result;
}
?>

                    <a href="javascript:void(0);" class="imageBtn" id="firstDisplay" title="<?php echo $firstDisplay; ?>">
                        <img src="<?php echo $baseURL; ?>/images/persons/<?php echo $firstDisplay; ?>.png" />
                        <?php // $scoreFD = getScore($firstDisplay); echo "Wins: ".$scoreFD["wins"]." Losses: ".$scoreFD["losses"].""; ?>
                    </a>

                    <a href="javascript:void(0);" class="imageBtn" id="secondDisplay" title="<?php echo $secondDisplay; ?>">
                        <img src="<?php echo $baseURL; ?>/images/persons/<?php echo $secondDisplay; ?>.png" />
                        <?php // $scoreSD = getScore($secondDisplay); echo "Wins: ".$scoreSD["wins"]." Losses: ".$scoreSD["losses"].""; ?>
                    </a>

it's all loading correctly, just the img/buttons wont submit/work after its reloaded.

You need to use the form $(document).on('event', '.selector', function(){}); to listen for new elements on the DOM and attach your handler to them.

The answer here is event delegation.

Binding an event listener to an object will not bind it to all other dynamically loaded or created objects, or adding the(lets say class as in your example) to another object will not apply its event listeners , since they did not exists when the script was run

$('.firstDisplay').on("click", function () {

you say all current elements with firstDisplay class do something on click. If you then add a new .firstDisplay, it wont know that it needs to listen to the on click. in short the listener is not attached on the class itself, but on the elements that have the class when the script is run.

now to get it to work, we will use event delegation

$(document).on("click",'.firstDisplay', function () {

this time around we bind the event on document. we also tell the event that should it find a firstdisplay class on an element clicked inside the document, the following function must be executed. So if new element are added, the event, bound to document now, will properly fire

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