每个内的 jQuery 变量范围
我正在尝试构建一个包含每个表单元素的所有值的数组。该警报仅适用于查找,但在 console.log 上数据为空,我是否无法理解 javascript 中的作用域如何工作?
var data = new Array();
$("#page2 input").each(function(index) {
alert($(this).attr('id'));
data[$(this).attr('id')] = $(this).val();
});
非常感谢您抽出时间,
I am trying to build an array containing all the values of every form element. The alert works just find, but on console.log data is empty, am I failing to understand how scoping in javascript works?
var data = new Array();
$("#page2 input").each(function(index) {
alert($(this).attr('id'));
data[$(this).attr('id')] = $(this).val();
});
Many thanks for your time,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
需要知道的一件事是 JavaScript 中的数组只能有正整数索引(实际上被视为字符串)。
当您将字符串分配给键时,您正在将属性分配给
对象
。您可能想要这样的东西...
jsFiddle。
如果您只需要
id
属性。jsFiddle。
One thing to know is that an
Array
in JavaScript can only ever have positive integer indexes (which are really treated as strings).When you assign a string to the key, you are assigning properties to an
Object
.You probably want something like this...
jsFiddle.
If you wanted just the
id
attributes.jsFiddle.
您正在尝试创建一个对象(
new Object()
或{ }
),而不是数组。You're trying to make an object (
new Object()
or{ }
), not an array.范围是正确的。如果控制台没有显示数组中的整体,那么我猜测您的 ID 属性不是数字。
并不意味着数据不存在。只是意味着控制台选择仅显示数字索引。
考虑 Chrome 控制台中的以下输入:
虽然为数组提供非数字属性是有效的 JavaScript,但在大多数情况下这是错误的方法。
The scope is correct. If the console is not displaying entires in the Array, then I'm guessing that your ID attributes are not numeric.
Doesn't meant that the data isn't there. Just means that the console chooses to only display the numeric indices.
Consider the following input into Chrome's console:
While it is valid JavaScript to give a non numeric property to an Array, in most cases it is the wrong approach.
你的问题是:
但您的选择器仅适用于一种特定表单的输入元素。假设您实际上想要表单中所有控件的值,那么以下 POJS 可能适合:
假设每个控件都有一个 ID,这不是必需的。如果某些控件没有 id,您可能需要使用 name 属性,因此:
在某些情况下,您的控件可能没有 id 或名称(例如,表单需要但其值不是的控件)被提交,例如提交和重置按钮)所以:
您可能还需要处理具有相同名称的控件,因为最后访问的控件的值将替换先前的同名控件的值。
Your question was:
but your selector was only for input elements in one particular form. Presuming that you actually wanted the values of all the controls in a form, then the following POJS may suit:
Presuming that every control has an ID, which is not a requirement. If some controls don't have an id, you might want to use the name property instead, so:
In some cases, your controls may not have an id or a name (e.g. controls that are needed for the form but whose values are not to be submitted, such as submit and reset buttons) so:
You may also need to deal with controls having the same name, since the value of whichever one is accessed last will replace the value of previous same-named controls.
如果您使用输入 id 作为键,那么您创建的是一个对象,而不是数组。
If you're using the input id as a key what you're creating is an Object, not an Array.