【问题标题】:populating JavaScript key value pair填充 JavaScript 键值对
【发布时间】:2014-06-06 08:26:24
【问题描述】:

我有一个带有文件名和复选框的表单,这些表单来自已经预先填充的服务器。我的表单应该更新复选框。

我的 JavaScript 代码可以选择行并尝试使用每行复选框中的更新值构建键值对象。

When the selector is set to only return the ones that are checked, the dictionary gets built perfectly, but I also want to add to the dictionary the entries that might have gotten ticked off.

当我让选择器选择所有行(包括未定义选中属性的位置)时,字典根本不会被填充。

这是我的输入元素:

<input type="checkbox" name="Map" data-id="@file.FileId" checked="checked" class="auto-accept-checkbox" />

这里是 javascript sn-p:

var map = {};

$("#shareable-file-settings-form table tr").each(function () {
    map[$(this).attr('data-id')] = $(this).attr('checked') === 'checked';
});

我已经在控制台上逐项尝试,我的右手操作数表达式在那里工作! I don't know why that look would misbehave like that (not putting anything in the dictionary) when the selector is modified

来自:

"#shareable-file-settings-form table tr :checked"

到:

"#shareable-file-settings-form table tr"

【问题讨论】:

  • 它不起作用,因为您选择的 tr 元素不能具有 checked 属性并且可能没有设置 data-id。您的第一个选择器正在工作,因为它正在选择您的 trs 的子级复选框。尝试#shareable-file-settings-form table tr input[type="checkbox"] 作为选择器。

标签: javascript jquery dictionary key-value


【解决方案1】:

就像乔说的那样,您选择的是 tr 元素,而不是里面的 input[type=checkbox]。首先,将您的选择器更改为

"#shareable-file-settings-form table tr input[type=checkbox]"

此外,复选框上的“checked”属性是 HTML 属性,而不是属性。另外,您可以使用 jQuery 的.data() 方法来访问id 数据属性。

你可以改成

map[$(this).data('id')] = $(this).prop('checked');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 2014-05-14
    • 1970-01-01
    • 2019-10-22
    相关资源
    最近更新 更多