gpt4 book ai didi

javascript - HTML 表格逐一显示 JQuery 复选框并且不保留数据

转载 作者:行者123 更新时间:2023-11-30 12:02:56 24 4
gpt4 key购买 nike

我有一些 JavaScript 代码应该显示一个复选框矩阵。我想在顶部列出列标题,然后在每个标题下有一列复选框的地方放置行,在空白标题框下加上一个带有行名称的左侧列。我要查看此页面上的外观:

http://codepen.io/marclundgren/pen/hgelI

我写了一个几乎可以工作的 Fiddle:

https://jsfiddle.net/bv01xvdf/

第一个问题是我的表在与行名称的单元格不同的行上显示复选框。我检查了我的 HTML,它似乎是正确的,但我想知道我是否缺少 <tr></tr>某处。我像这样添加行名称单元格(完整代码请参见 Fiddle):

var chugNames = ["Ropes", "Cooking", "Outdoor Cooking"];
for (x = 0; x < chugNames.length; x++) {
// Add a row for each name.
target.append("<tr><td>" + chugNames[x] + "</td>");
for (y = 0; y < chugNames.length; y++) {
target.append("<td><input type=\"checkbox\" />");
checkbox = $('</input>', {
'type': 'checkbox',
'data-x': chugNames[x],
'data-y': chugNames[y],
});
target.append(checkbox);
target.append("</td>");
}
target.append("</tr>");
}

另一个问题是,当我稍后在“on”方法中访问它们时,data-x 和 data-y 返回“undefined”:

   target.on('change', 'input:checkbox', function() {
var $this = $(this),
x = $this.data('x'),
y = $this.data('y'),
checked = $this.prop('checked');
alert('checkbox changed chug intersection (' + x + ', ' + y + '): ' + checked);
});

当我选中一个框时,我得到“checkbox changed chug intersection (undefined, undefined): true”。它应该打印类似(绳索, cooking )的内容,具体取决于选中的框。

如有任何帮助,我们将不胜感激。

最佳答案

当您附加 jQuery 时,标签会自动关闭。

check the jsfiddle

试试这个:

$(function() {
var target = $('#checkboxes');
var chugNames = ["Ropes", "Cooking", "Outdoor Cooking"];
var i, x, y, checkbox, html;
html = "<table class=\"responsive-table-input-matrix\"><thead><tr><th></th>";
// Table column headers
for (i = 0; i < chugNames.length; i++) {
html += "<th>" + chugNames[i] + "</th>";
}
html += "</tr></thead><tbody>";

for (x = 0; x < chugNames.length; x++) {
// Add a row for each chug.

html += "<tr><td>" + chugNames[x] + "</td>";

for (y = 0; y < chugNames.length; y++) {
html += "<td>";
checkbox = '<input type=checkbox ';
checkbox += ' data-x=' + chugNames[x]
checkbox += ' data-y=' + chugNames[y]
checkbox += '/>'
html += checkbox;
html += "</td>";
}
html += "</tr>";
}
html += "</tbody></table>";

target.append(html).width(function() {
return $(this).find("input:checkbox").outerWidth() * chugNames.length
});

target.on('change', 'input:checkbox', function() {
var $this = $(this),
x = $this.data('x'),
y = $this.data('y'),
checked = $this.prop('checked');
alert('checkbox changed chug intersection (' + x + ', ' + y + '): ' + checked);
});

});

关于javascript - HTML 表格逐一显示 JQuery 复选框并且不保留数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36187438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com