我试图创建一个输入表,当您在底线的输入之一中输入文本时,它会自动添加新行。大多数情况下,它工作正常。不过,我在使用jQuery UI复选框按钮时遇到了一些麻烦。jQuery UI复选框在克隆时行为异常
复选框按钮应单击时更改其图标。这适用于原始按钮,但添加新行时出现的克隆按钮无法正常工作。
你可以看到它in jsfiddle here。要复制这个问题,请在第三个输入中输入一些文字。你会看到第四行出现。如果您按第四个复选框,您会看到第三个复选框是其图标更改的复选框。错误的按钮也会得到ui-state-focus,但实际上并没有获得焦点,这真的让我感到困惑,虽然正确的按钮确实获得了ui状态激活,并且据我所知,看起来似乎评估为已被检查正常。
要清楚,两个复选框做不是具有相同的ID,并且它们的标签是正确的复选框 - createNewRow()函数负责。如果你注释掉将复选框变成jQuery UI复选框的行,你会看到一切正常。如果你在buttonSwitchCheck函数中console.log $(this).attr('id')的值,你会发现它也有正确的ID - 如果你点击第四个按钮,它会告诉你$(this)的id是“test4”,但它是“test3”(第三个按钮),它会改变图标。
我疯了盯着这个,我会很感激任何帮助的人可以给。下面的代码:
// Turns on and off an icon as the checkbox changes from checked to unchecked.
function buttonSwitchCheck() {
if ($(this).prop('checked') === true) {
$(this).button("option", "icons", {
primary: "ui-icon-circle-check"
});
} else {
$(this).button("option", "icons", {
primary: "ui-icon-circle-close"
});
}
}
// Add a new row at the bottom once the user starts filling out the bottom blank row.
function createNewRow() {
// Identify the row and clone it, including the bound events.
var row = $(this).closest("tr");
var table = row.closest("table");
var newRow = row.clone(true);
// Set all values (except for buttons) to blank for the new row.
newRow.find('.ssheet').not('.button').val('');
// Find elements that require an ID (mostly elements with labels like checkboxes) and increment the ID.
newRow.find('.ssheetRowId').each(function() {
var idArr = $(this).attr('id').match(/^(.*?)([0-9]*)$/);
var idNum = idArr[2] - 0 + 1;
var newId = idArr[1] + idNum;
$(this).attr('id', newId);
$(this).siblings('label.ssheetGetRowId').attr('for', newId);
});
// Add the row to the table.
newRow.appendTo(table);
// Remove the old row's ability to create a new row.
row.removeClass('ssheetNewRow');
row.find(".ssheet").unbind('change', createNewRow);
}
$(document).ready(function() {
// Activate jQuery UI checkboxes.
$(".checkButton").button().bind('change', buttonSwitchCheck).each(buttonSwitchCheck);
// When text is entered on the bottom row, add a new row.
$(".ssheetNewRow").find(".ssheet").not('.checkButton').bind('change', createNewRow);
});
编辑:我能够找到一个解决方案,我将与年龄分享。感谢下面的“Funky Dude”,他激励我开始思考正确的道路。
诀窍是在克隆之前销毁原始行中的jQuery UI按钮,然后在原始行和副本之后立即重新初始化它。您不需要解除绑定并重新绑定更改事件 - 它只是有问题的jQuery UI按钮。在createNewRow功能:
row.find('.checkButton').button('destroy');
var newRow = row.clone(true);
row.find('.checkButton').add(newRow.find('.checkButton')).button().each(buttonSwitchCheck);
我已经尝试过这样做;没有快乐。但是,谢谢。 – flyingGhoti 2013-02-12 18:36:15
啊 - 但我没有试过的是在按钮克隆之前销毁按钮,然后重新创建按钮! – flyingGhoti 2013-02-12 18:43:43