为什么当我点击按钮时网页刷新,而不是在控制台调用按钮的功能

Why is webpage refreshing when I click on a button and not when call the function of the button in the console

本文关键字:按钮 控制台 功能 调用 刷新 为什么 网页      更新时间:2023-09-26

如果我在浏览器的javascript控制台上直接调用我的函数,它不会按预期刷新我的网页但如果我用按钮来做,它会:

我已经尝试过这个我的jquery ajax代码刷新页面没有理由,但它似乎不适合我

$('<button>')
            .attr('onclick',"nextQuestion()")
            .attr('class', "btn btn-success")
            .html('Suivant') 

按钮的默认typesubmit,因此当您单击表单中的按钮时,它将默认提交表单。

这是导致页面刷新的原因。

您可以通过设置type=button

来防止这种情况
$('<button>', {type: 'button'})
        .attr('onclick',"nextQuestion()")
        .attr('class', "btn btn-success")
        .html('Suivant')
$( 'button' ).on('click' , nextQuestion).attr('class', "btn btn-success").html('Suivant') ;

我建议您在按钮上使用ID,并替换button, with #ButtonID '。