簡體   English   中英

jQuery不響應AJAX加載的內容

[英]jQuery not responding to AJAX loaded content

我有一個新聞源頁面,當頁面加載時,我在其中加載了8個項目,當用戶向下滾動到頁面底部時,它將再加載8個項目。 加載項目不是問題。 在頁面中,我有一個jquery腳本,如果用戶按Enter鍵,則提交表單;如果用戶在注釋框中按shift + enter,則轉到下一行。 它適用於前8個項目,但不適用於AJAX加載的項目。

我應該怎么做才能使jquery函數對通過AJAX加載的項目起作用?

這是feed.php頁面:

<?php
    require 'includes/master.php';
    include 'includes/header.php';
?>


<div class="container">
    <p>
        <!--UPDATE STATUS-->  
        <div class="row" style="margin-bottom:25px;">
            <div class="col-lg-3"></div>
            <div id="postedFeeds" class="col-lg-6">
                <form action="" method="post" id="updateStatus">
                    <textarea name="status" class="updateStatusInput" placeholder="What's going on?"></textarea>
                    <input type="submit" name="submitstatus" value="Update" class="statussubmit hidden">
                </form>
                <?php getNewsFeed(); ?> <!--LOAD FIRST 8 ITMES-->
            </div>
            <div class="col-lg-3"></div>
        </div><!--end div class row-->

        <div id="loadMoreFeed" style="display:none;" ></div>
    </p>
</div><!--end container div-->

<div style="clear:both;"></div>


<!--SCRIPT TO LOAD NEXT 8 ITEMS-->
<script>
$(document).ready(function() {
    doMouseWheel1 = 1 ;
    $("#postedFeeds").append( "<p id='feedlast'></p>" );

    $(window).on('scroll', function() {
        if (!doMouseWheel1)
            return;
        var distanceTop1 = $('#feedlast').offset().top - $(window).height();
        if  ($(window).scrollTop() > distanceTop1) {
            $('div#loadMoreFeed').show();
            doMouseWheel1 = 0 ;
            $.ajax({
                dataType : "html",
                url: "process/loadMoreFeed.php?lastPost="+ $(".postSection:last").attr('id'),
                success: function(html1) {
                    doMouseWheel1 = 1 ;
                    if(html1){
                        $("#postedFeeds").append(html1);
                        $("#feedlast").remove();
                        $('textarea').autosize();
                        $("#postedFeeds").append( "<p id='feedlast'></p>" );
                        $('div#loadMoreFeed').hide();
                    } else {
                        //Disable Ajax when result from PHP-script is empty (no more DB-results )
                        $('div#loadMoreFeed').replaceWith( " " );
                        doMouseWheel1 = 0 ;
                    }
                }
            });
        }
    });
});

<!--END SCRIPT TO LOAD NEXT 8 ITEMS-->

<!--AUTO RESIZE PLUGIN-->
$('textarea').autosize();



<!--SCRIPT TO SUBMIT FORM WHEN ENTER PRESSED AND NEW LINE WHEN SHIFT+ENTER PRESSED-->
$(function(){
    $('.commentTextarea').keypress(function(event){
        var id = $(this).closest(".commentForm").data("id");
        if (event.keyCode==13 && !event.shiftKey) {
            event.preventDefault();
            $(this).closest(".commentForm[data-id='"+id+"']").submit();
            return false;
        }
    });

<!--SCRIPT TO SUBMIT COMMENT ON ENTER-->
    $(".commentForm").submit(function(event1) {
        // Stop form from submitting normally
        event1.preventDefault();

        // Get some values from elements on the page:
        var $form = $(this),
        activityid = $form.data("id"),
        comment = $form.find( "textarea[name='comment']" ).val(),
        url = "process/insertComment.php";

        // Send the data using post
        var posting = $.post( url, { activityid: activityid, comment: comment } );

        // Put the results in a div
        posting.done(function( data ) {
            $form.find('.commentTextarea').val('');
        });
        return false;
    });
});


<!--SCRIPTS TO LOAD COMMENTS-->
$(document).ready(function(){
    var id = $('.commentsContent').data("id");
    $(".commentsContent[data-id='"+id+"']").load("process/loadComments.php?activityid="+id);
});

window.setInterval(function(){
    var id = $('.commentsContent').data("id");
    $(".commentsContent[data-id='"+id+"']").load("process/loadComments.php?activityid="+id);
}, 3000);
</script>


<?php
    include 'includes/footer.php';
?>

這是getNewsFeed()

/*PHP variables set above.  Too long to show*/

        echo "
        <div class='postSection' id='$activityid'>
            <div class='postedFeed'>
                <div class='activitypost'>
                    <!--IMAGE-->
                    <div class='postImageSection'>
                        <p><a href='/$activityusername'><img class='postImage' src='$activityprofilephoto'></a></p>
                        <p class='postUsername'><a href='/$activityusername'>$activityusername</a></p>
                    </div>

                    <!--CONTENT-->
                    <p class='postContent'>
                    ";

                        if ($activitytype=="accountcreated") {
                            echo "<a href='/$activityusername'>$activityusername</a> joined StemEdNet!";
                        }
                        elseif ($activitytype=="status") {
                            echo "$activitycontent";

                            if ($activityfileid != "0") {
                                if ($filetype=="image/jpeg" || $filetype=="image/png"  || $filetype=="image/gif" || $filetype=="image/jpg") {
                                    echo "<div style='margin-top:10px;'><a href='$filelink' data-lightbox='image-$activityfileid'><img class='thumb' src='$filelink'></a></div>";
                                }

                                elseif ($filetype=="audio/mp3" || $filetype=="audio/mp4"  || $filetype=="audio/mpeg") {
                                    echo "<div style='margin-top:10px;'>
                                    <audio width='100' controls>
                                      <source src='$filelink' type='audio/mpeg'>
                                      <source src='$filelink' type='audio/mp4'>
                                      <source src='$filelink' type='audio/mp3'>
                                      <embed height='50' width='100' src='$filelink'>
                                    </audio>
                                    </div>";
                                }

                                elseif ($filetype=="video/mp4" || $filetype=="video/mpeg") {
                                    echo "
                                    <div style='margin-top:0px;'>
                                    <video width='140' height='240' controls>
                                        <source src='$filelink' type='video/mp4'>
                                        <source src='$filelink' type='video/mpeg'>
                                    </video>
                                    </div>
                                    ";
                                }
                                else {
                                    echo "<div style='margin-top:10px;'><a target='_blank' href='?getfile=$activityfileid'>Download</a></div>";
                                }
                            }
                        }

                    echo"
                    </p>
                </div>

                <div style='clear:both;'></div>
            </div>

            <div class='commentSection'>
                <div class='commentsContent' data-id='$activityid'>
                    <!--Comments are loaded into here using jQuery-->
                </div>
                <form class='commentForm' action='' data-id='$activityid'>
                    <textarea name='comment' class='commentTextarea' placeholder='Comment...'></textarea>
                    <input type='submit' class='hidden' name='commentsubmit' value='Comment'>
                </form>
            </div><!--end commentSection-->
            ";
        echo "</div>";//end col-lg-8
    }//end while
}//end getNewsFeed()

問題是.keypress()函數。 您需要對委托的事件使用jquery的.on()函數。

當您使用.keypress()時,它將事件處理程序附加到當時存在的任何.commentTextArea元素上。 通過滾動添加新的commentTextArea元素時,它不會將keypress事件處理程序附加到這些新的元素上。 當您使用.on()函數時,即使稍后添加新的commentTextAreas,它也會響應。 因此,您可以這樣重寫它:

$('#postedFeeds').on('keypress', '.commentTextarea', function(event){
    var id = $(this).closest(".commentForm").data("id");
    if (event.keyCode==13 && !event.shiftKey) {
        event.preventDefault();
        $(this).closest(".commentForm[data-id='"+id+"']").submit();
        return false;
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM