【问题标题】:Why is webpage refreshing when I click on a button and not when call the function of the button in the console为什么单击按钮时网页刷新而不是在控制台中调用按钮的功能时
【发布时间】:2015-08-10 05:16:07
【问题描述】:

如果我直接在浏览器的 javascript 控制台中调用我的函数,它不会按预期刷新我的网页,但如果我使用按钮执行此操作,它会:

我已经尝试过这个My jquery ajax code refresh the page without reason,但它似乎不适合我

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

【问题讨论】:

  • 可能包含这个功能?
  • 请显示更多您的 HTML(例如,button 绝不是提交按钮,对吧?)以及您的 nextQuestion 函数的作用。
  • 谢谢,我会在几分钟后把html放到网上,这不是提交按钮。
  • 确保在问题本身中包含函数...
  • 按钮是否在表单内?它是表单中唯一的按钮吗?它有类型属性吗?

标签: javascript jquery


【解决方案1】:

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

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

你可以通过设置type=button来防止这种情况

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

【讨论】:

    【解决方案2】:
    $( 'button' ).on('click' , nextQuestion).attr('class', "btn btn-success").html('Suivant') ;
    

    我建议你在按钮上使用一个ID,并替换button, with#ButtonID`。

    【讨论】:

    • 我尝试过这样做,但它似乎不起作用,但无论如何我都会有这个按钮的 id :)
    猜你喜欢
    • 2017-10-16
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 2015-07-05
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多