crj*_*unk 4 html javascript jquery
我遇到了代码中的错误.我正在克隆div,以便用户可以添加多个客户.
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
var newElem = $('#divInput' + num).clone().attr('id', 'divInput' + newNum); // create the new element via clone(), and manipulate it's ID using newNum value
// clear input value for cloned items and do not remove text for del button.
newElem.find('input:not(.DeleteBtn),textarea').val('');
//newElem.find('input[type="submit"]
// Replace clone num with incremental num.
newElem.find(':input').each(function () {
$(this).attr('id', $(this).attr('id').replace(/\d+/, newNum));
$(this).attr('name', $(this).attr('name').replace(/\d+/, newNum));
});
// insert the new element after the last "duplicatable" input field
$('#divInput' + num).after(newElem);
Run Code Online (Sandbox Code Playgroud)
我提供了删除按钮来删除行,我使用按钮的类名来执行单击时的功能.
$(".DeleteBtn").click(function () {
alert(".DeleteBtn Click Function - " + $(this).attr('id'));
var DelBtnNum = $(this).attr('id');
DelBtnNum = DelBtnNum[DelBtnNum.length - 1];
$('#divInput' + DelBtnNum).remove();
});
Run Code Online (Sandbox Code Playgroud)
我可以删除第一个(原始)输入行,但不会删除任何其他客户行.
我在这里有一个代码的运行演示:http://jsfiddle.net/crjunk/FB4BZ/2/
为什么克隆的项目不会触发.DeleteBtn.click函数?
您需要使用事件委派来支持动态元素.
因为你在小提琴中使用了jQuery 1.6
$(document).delegate(".DeleteBtn", 'click', function () {
alert(".DeleteBtn Click Function - " + $(this).attr('id'));
var DelBtnNum = $(this).attr('id');
DelBtnNum = DelBtnNum[DelBtnNum.length - 1];
$('#divInput' + DelBtnNum).remove();
});
Run Code Online (Sandbox Code Playgroud)
如果jQuery> = 1.7
$(document).on('click', ".DeleteBtn", function () {
alert(".DeleteBtn Click Function - " + $(this).attr('id'));
var DelBtnNum = $(this).attr('id');
DelBtnNum = DelBtnNum[DelBtnNum.length - 1];
$('#divInput' + DelBtnNum).remove();
});
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用事件克隆元素和事件 clone(true)
因为使用克隆时的默认设置是不克隆事件.尝试传递true给clone():
var newElem = $('#divInput' + num).clone(true).attr('id', 'divInput' + newNum); // create the new element via clone(), and manipulate it's ID using newNum value
Run Code Online (Sandbox Code Playgroud)
正如.clone()文档所述:
.clone([withDataAndEvents])withDataAndEvents(默认值:false)
绑定click事件时,只存在一个div,因此它是唯一一个具有单击处理程序的div.您应该更改要使用的代码而不是单击.
$(document).on('click', ".DeleteBtn", function () {
Run Code Online (Sandbox Code Playgroud)