简体   繁体   English

用jQuery遍历变量不起作用

[英]Iterating over variable with jQuery not working

I set this variable at the top of my page setVars = {"n":"2","m":"1","degree":"3","p":"2"} 我在页面顶部设置此变量setVars = {"n":"2","m":"1","degree":"3","p":"2"}

I want to iterate over each of the elements in setVars but jquery's each() function isn't working. 我想遍历setVars中的每个元素,但是jquery的each()函数不起作用。

Here's what I have - 这就是我所拥有的-

$(setVars).each(function(key, value) {
  elementId = '#' + key+ '-wrapper';
}

But key is set to 0 here on the first iteration and value is set to the full setVars object here for some reason. 但是由于某种原因,此处在第一次迭代中将key设置为0,并在此处将value设置为完整的setVars对象。 It doesn't make it to a second iteration, it breaks when I step through it and try to go to the second iteration. 它不会进行第二次迭代,而是在我逐步执行并尝试进行第二次迭代时会中断。

It should be like that I belive according to this http://api.jquery.com/jQuery.each/ 根据这个http://api.jquery.com/jQuery.each/我应该相信

$.each(setVars, function(key, value) {
  elementId = '#' + key+ '-wrapper';
});

setVars is not a collection of DOM elements, it is an object setVars不是DOM元素的集合,而是一个对象

You are using .each() that's meant for iterating through jQuery objects instead of $.each() that's meant for iterating through objects and arrays . 您正在使用.each()来遍历jQuery对象,而不是$.each()来遍历对象和数组 Try this: 尝试这个:

$.each( setVars, function(key, value) {
  elementId = '#' + key+ '-wrapper';
});

you don't need JQuery for this. 您不需要JQuery。 Also I could be wrong but you don't want the quotes around the name of the object properties you never see that: 同样,我可能是错的,但是您不希望对象属性名称周围的引号永远不会出现:

setVars = {n:"2",m:"1",degree:"3",p:"2"}

And

for(i in setVars){
   console.log("key: ",i," value: ", setVars[i]); // demonstration of how to access key and value
   elementId = '#' + i + '-wrapper';
}

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

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