Div内容在出现几毫秒后消失

Div contents disappears about milliseconds of appearing

本文关键字:几毫 消失 Div      更新时间:2023-09-26

HTML:

<form id='pool_play'>
    <?php           
        $PLAYERS = 8;
        for ($i=1; $i <= $PLAYERS; $i++) { 
            print $i . ' <input type="text" class="initial_players" autofocus> <br/>';
        }
    ?>
    <br>
    <button type="submit" class="random"> Randomize bracket</button>
</form>
<p class="debug"></p>

js:

$("#pool_play").submit(function(event) {
    var participants = $('.initial_players').map(function() {
        return $(this).val();
    }).get();
    for (var i = 0; i < participants.length; i++) {
        $('p.debug').append(participants[i] + " ");
    }
});

我主要想做的是,当提交#pool_play的表单时,打印.debug段落标记中输入框的内容。结果是,它出现了几毫秒,然后消失了。我的猜测是,当页面提交时,旧数据(即.debug段落填充后的内容(会被丢弃。小贴士?

您需要阻止提交操作,否则页面将在不更改页面的情况下重新加载。

$("#pool_play").submit(function(event) {
    var participants = $('.initial_players').map(function() {
        return $(this).val();
    }).get();
    for (var i = 0; i < participants.length; i++) {
        $('p.debug').append(participants[i] + " ");
    }
    event.preventDefault();
    return false;
});

然而,将按钮更改为button而不是submit 可能是一个更好的主意

<button type="button" class="random"> Randomize bracket</button>

您可以使用event.preventDefault() 阻止页面提交

$("#pool_play").submit(function(event) {
    var participants = $('.initial_players').map(function() {
        return $(this).val();
    }).get();
    for (var i = 0; i < participants.length; i++) {
        $('p.debug').append(participants[i] + " ");
    }
    event.preventDefault();//stops submit
});

查看代码。您正在捕捉submit事件,正在获取打印它们的数据。。。然后你退出了你的功能,所以submit事件的默认操作是由浏览器执行的,因为你没有停止它。这就是为什么你只能在毫秒内看到这些内容——浏览器正在刷新页面。

您应该使用event.preventDefault()功能来防止浏览器在执行您的功能后提交表单。