简体   繁体   English

填充JavaScript键值对

[英]populating JavaScript key value pair

I have a form with file-names and check-boxes that comes from the server already pre-populated. 我有一个带有文件名和复选框的表单,该表单来自已经预先填充的服务器。 My form is supposed to update the check boxes. 我的表格应该更新复选框。

I have code in JavaScript that selects the rows and attempts to build a key value object with the updated values from the check-boxes in each row. 我在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. 当选择器设置为仅返回已检查的选择器时,该字典将得到完美构建,但是我也想将可能已被选中的条目添加到字典中。

When I make the selector select all rows (including where the checked attribute is undefined) then the dictionary doesn't get populated at all. 当我使选择器选择所有行(包括未定义checked属性的行)时,根本不会填充字典。

Here is my input element: 这是我的输入元素:

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

Here is the javascript snippet: 这是javascript代码段:

var map = {};

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

I have tried on the console item by item and my right hand operand expression works there! 我已经逐项尝试了控制台,并且我的右操作数表达式在这里起作用了! I don't know why that look would misbehave like that (not putting anything in the dictionary) when the selector is modified 我不知道为什么在修改选择器后,外观看起来会像这样(不在字典中放任何东西)

from: 从:

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

to: 至:

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

Like Joe said, you're selecting the tr element, not the input[type=checkbox] inside. 就像乔所说的,您选择的是tr元素,而不是内部的input[type=checkbox] First, change your selector to 首先,将选择器更改为

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

Further, the "checked" property on checkboxes is an HTML property, not an attribute. 此外,复选框上的“选中”属性是HTML属性,而不是属性。 Also, you can use jQuery's .data() method to access the id data attribute. 另外,您可以使用jQuery的.data()方法访问id数据属性。

You can change it to 您可以将其更改为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM