jQuery/Javascript不适用于动态网页

jQuery/Javascript not working on dynamic web pages

本文关键字:动态 网页 适用于 不适用 Javascript jQuery      更新时间:2023-09-26

我有一个脚本,它在静态网页上运行得很好,但我无法让它在动态网页上运行。我尝试了与我所做的研究不同的技术,但我仍然无法使其发挥作用,所以我正在寻求帮助。

我的脚本:

<script type="text/javascript" src="http://mywebsite.com/js/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $(document).on('submit', '#bv-form', function() {
            var data = $(this).serialize();
            $.ajax({
            type: 'POST',
            url: 'notify.php',
            data: data,
            success: function(data) {
                $("#bv-form").fadeOut(500).hide(function() {
                    $(".form-result").fadeIn(500).show(function() {
                        $(".form-result").html(data);
                    });
                });
            }
        });
        return false;
    });
});

形式:

<form method="post" id="bv-form">
    <div class="checkbox form-feedback margin-five m_top_20">
        <!-- checkbox  -->
        <label><input type="checkbox" name="video_title" id="publish" checked value="<?php echo ucwords($row['video_title']); ?>"> <em>"<?php echo ucwords($row['video_title']); ?>"</em> by <b><?php echo ucwords($row['artist_name']); ?></b> is not working</label>
        <!-- end checkbox  -->
    </div>
    <div class="form-group">
        <!-- button  -->
        <button class="btn btn-black no-margin-bottom btn-small no-margin-top" id="submit" type="submit">Send</button>
        <!-- end button  -->
        <input type="hidden" id="id"> 
        <input type="hidden" id="video_id" name="video_id" value="<?php echo ucwords($row['id']); ?>"> 
        <input type="hidden" id="artist_name" name="artist_name" value="<?php echo $row['video_title']; ?>"> 
    </div>
</form>

我正在使用.on(),但有什么东西我遗漏了吗?

注意:我知道这个问题以前在这个网站上被问过。我已经尝试过在这些解决方案中遵循某些步骤,但我仍然无法让这个脚本发挥作用。

如果表单是动态的,意味着它在页面加载后被添加到页面中,那么提交很可能不会启动,因为它找不到表单。

试试这个:

$(document).find("#bv-form").on('submit', function(){ ... });

这会在DOM中搜索ID,而不是假设它在那里。