javascript 单击按钮时重复 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21135520/
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
Repeat a div when clicking a button
提问by user3189828
The below code is for repeating a div. But it does not work. Please help me.
下面的代码用于重复一个 div。但它不起作用。请帮我。
<html>
<head>
<script>
$(".repeat").live('click', function () {
var $self = $(this);
$self.after($self.parent().clone());
$self.remove();
});
</script>
</head>
<body>
<form>
<div class="repeatable">
<table border="1">
<tr><td><input type="text" name="userInput[]"></td></tr></table>
<button class="repeat">Add Another</button>
</div>
<input type="submit" value="Submit">
</form>
</body>
</html>
回答by Rohan Kumar
First add jquery
in your code
and use on()in place of live().
首先添加jquery
您code
并使用on()代替live()。
Also write your code in $(function(){...})
so, that your code will work after document ready
还要编写您的代码,$(function(){...})
以便您的代码在之后工作document ready
<script src="http:/code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$(".repeat").on('click', function () {
var $self = $(this);
$self.after($self.parent().clone());
$self.remove();
});
});
</script>
Updated,if you want it to work for more inputs
then try this,
更新,如果你想让它工作,more inputs
那么试试这个,
$(function () {
$(".repeat").on('click', function (e) {
e.preventDefault();// to prevent form submit
var $self = $(this);
$self.before($self.prev('table').clone());// use prev() not parent()
//$self.remove();// remove this line so you can add more inputs
});
});
回答by Peter Bankuti
use
利用
$(document).on('click', '.repeat', function () {
instead of
代替
$(".repeat").live('click', function () {
回答by Pragmatist
The $(".repeat")
construction says that jQuery must be used.
Try to add <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
before your <script>
该$(".repeat")
构造表示必须使用 jQuery。尝试<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
在您之前添加<script>
回答by Robin C Samuel
Try this
试试这个
HTML
HTML
<body>
<form>
<div class="parent">
<div class="repeatable">
<table border="1">
<tr><td><input type="text" name="userInput[]"></td></tr></table>
<button class="repeat">Add Another</button>
</div>
</div>
<input type="submit" value="Submit">
</form>
</body>
Jquery
查询
$(document).on('click', '.repeat', function (e) {
e.preventDefault();
$('.repeatable').parent('div.parent').append($('.parent').children('div:first').html());
});
See jsfiddle,
见jsfiddle,