【问题标题】:jQuery not responding to AJAX loaded contentjQuery 不响应 AJAX 加载的内容
【发布时间】:2014-04-16 02:29:08
【问题描述】:

我有一个新闻提要页面,当页面加载时我加载了 8 个项目,当用户向下滚动到页面底部时,它将再加载 8 个项目。加载项目不是问题。在页面中,我有一个 jquery 脚本,如果用户按下回车,则提交表单,如果用户在评论框中按下 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()

【问题讨论】:

  • 看看 jQuery on() 函数和委托。 api.jquery.com/on
  • @JayBlanchard 我确实从以前的帖子中看到了这一点,我在脚本$(window).on('scroll', function() 的滚动事件中使用了它。我应该特别关注哪一部分?
  • 任何时候你想要对动态添加到 DOM 的东西(客户端)采取行动,你需要通过某种事件委托来处理它。 jQuery(javascript) 在添加时不会“看到”这些东西,因为它已经运行了。但是,如果您提供一些事件委托,jQuery(javascript) 将“看到”这些事件,因为它们冒泡到在页面加载期间运行 jQuery(javascript) 时存在的元素。

标签: javascript php jquery html ajax


【解决方案1】:

问题在于 .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;
    }
});

【讨论】:

  • 如果我使用#postedFeeds 作为目标,我不应该使用var id = $(this).closest(".commentForm").data("id"); 以外的东西吗?我需要找到我正在输入的特定 .commentTextarea,以便获得 .commentForm 数据 ID。对吗?
  • 当你像这样使用 .on() 时,$(this) 实际上是指用户输入的具有 '.commentTextArea' 类名的元素,所以你不必更改该行。
  • 明白了。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2013-08-06
  • 1970-01-01
  • 2011-01-21
  • 1970-01-01
  • 2013-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多