[英]Repeat a div when clicking a button
The below code is for repeating a div. 以下代码用于重复div。 But it does not work.
但这行不通。 Please help me.
请帮我。
<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>
First add jquery
in your code
and use on() in place of live() . 首先在
code
添加jquery
并使用on()代替live() 。
Also write your code in $(function(){...})
so, that your code will work after document ready
同时在
$(function(){...})
编写您的代码,以便您的代码在document ready
后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
});
});
use 采用
$(document).on('click', '.repeat', function () {
instead of 代替
$(".repeat").live('click', function () {
The $(".repeat")
construction says that jQuery must be used. $(".repeat")
结构表示必须使用jQuery。 Try to add <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
before your <script>
尝试在
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
之前添加<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
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 jQuery的
$(document).on('click', '.repeat', function (e) {
e.preventDefault();
$('.repeatable').parent('div.parent').append($('.parent').children('div:first').html());
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.