简体   繁体   English

动态加载新内容后,jQuery触发器不起作用

[英]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. 我正在制作一个使用图像的投票系统,每当您单击其中一个图像时,它将提交该图像,然后淡出并使用php页面重新加载它。 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 投票.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

<?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. 一切都正确加载,只是img /按钮在重新加载后不会提交/工作。

You need to use the form $(document).on('event', '.selector', function(){}); 您需要使用$(document).on('event', '.selector', function(){}); to listen for new elements on the DOM and attach your handler to them. 侦听DOM上的新元素并将您的处理程序附加到它们。

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. 您说的是firstDisplay类的所有当前元素在单击时都会执行某些操作。 If you then add a new .firstDisplay, it wont know that it needs to listen to the on click. 如果您随后添加一个新的.firstDisplay,它将不会知道需要监听点击。 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. 我们还告诉事件,如果它在文档内单击的元素上找到firstdisplay类,则必须执行以下函数。 So if new element are added, the event, bound to document now, will properly fire 因此,如果添加了新元素,则立即绑定到该文档的事件将正确触发

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

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