jQuery的包裹与形式的div没有提交

问题描述:

我有以下代码:jQuery的包裹与形式的div没有提交

HTML:

<button id="my_button">Test</button> 

的Javascript(jQuery的):

$(document).ready(function() { 
    $('#my_button').click(function() { 
    $(this).wrap('<form>') 
    }) 
}) 

当有按钮点击它用我希望的形式包装它,但也提交表格。

我只想用形式来包装没有提交它

无论是添加调用preventDefault

$(document).ready(function() { 
    $('#my_button').click(function(e) { 
    // Accept the arg -------------^ 
     e.preventDefault();  // Prevent the default action 
     $(this).wrap('<form>') 
    }); 
}); 

...或更改按钮的类型button

<button type="button" id="my_button">Test</button> 

...因为默认typebuttonsubmit

+0

谢谢,对于的情况,我应该使用preventDefault()? –

+0

@OmerNizri:是的,他们也提交表格。 –

您需要设置type属性与价值button将其转换成一个简单的按钮,否则充当submit按钮。

<button type="button" id="my_button">Test</button> 
+0

这是否确实解决了问题,还是应该这样评论? –

+2

@TimothyGroote:是的,这解决了这个问题。 'button'的默认'type'是'submit'。通过将其更改为'button',它不再提交表单。 –