javascript 按下按钮而不重新加载时,将 HTML 表单字段添加到现有表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9630854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:16:42  来源:igfitidea点击:

Add HTML form field to existing form when a button is pressed without reloading

javascriptjqueryhtmlforms

提问by Daniel Klose

I found quite a few JavaScriptexamples when googling for this. However, none of them worked for me.

我在谷歌搜索时发现了很多JavaScript示例。然而,他们都没有对我来说有效。

I want to achieve a relatively simple task: By pressing an add field button in a form a second select field should show up. This should go on indefinitely. Since I'm already using the jQuerylibrary, I would prefer to use it here too.

我想完成一个相对简单的任务:通过按下表单中的添加字段按钮,第二个选择字段应该会出现。这应该无限期地持续下去。由于我已经在使用jQuery库,因此我也更愿意在这里使用它。

The page should not reload once you press the add field button.

按添加字段按钮后,页面不应重新加载。

回答by Henrik Andersson

Use the append method for easy scripting. If, however, you want to do this on a more serious basis, read up on DOMscripting.

使用 append 方法可以轻松编写脚本。但是,如果您想更认真地执行此操作,请阅读DOM脚本。

See:

看:

回答by Patrick

Try the after(), append()and appendTo()methods (see Category: Manipulation).

尝试after(),append()appendTo()方法(参见类别:操作)。

回答by dankyy1

回答by ThomasM

This is very easy to do. Either you append a new element, like so:

这很容易做到。要么添加一个新元素,如下所示:

$("form").append($('<input type="text">');

OR, you already put the HTMLin the form, but make it invisible with CSSand then show it, like so:

或者,您已经将HTML放入表单中,但使用CSS使其不可见,然后显示它,如下所示:

<form>
    <input type="text" class="hidden">
</form>

$("#theNewField").removeClass('hidden');

回答by dmc

var newSelectField = "<select><option>Option 1</option><option>Option 2</option></select>"; 

$("#formID").append(newSelectField);

//make sure your button is not of type="submit"
<input type="button" value="Add new field" />

回答by Anthony

Without sample code, I can only guess what the issue is, but it sounds like you are using a submit input instead of a button input, which is causing your form to submit and the page to reload instead of just triggering the "add element" function. If that's the case, here's what to do:

没有示例代码,我只能猜测问题是什么,但听起来您使用的是提交输入而不是按钮输入,这会导致您的表单提交和页面重新加载,而不仅仅是触发“添加元素”功能。如果是这种情况,请执行以下操作:

Change the add button to look like:

将添加按钮更改为如下所示:

 <input type="button" id="addOption" value="Add" />

If it's not already in place, add the event listener in your script for when the button is clicked:

如果它还没有到位,请在您的脚本中添加单击按钮时的事件侦听器:

 $("#addOption").click (function(){
 // Add stuff
}):

Follow Patrick's advice on the jQuerymanipulation methods.

遵循 Patrick 关于jQuery操作方法的建议。