简体   繁体   English

在带有JSON对象的jQuery中使用.each时,如何避免未定义的属性?

[英]When using .each in jQuery with a JSON object how do I avoid undefined properties?

I'm attempting to fill the values of <inputs> on a page using the data from a JSON object. 我正在尝试使用JSON对象中的数据填充页面上<inputs>的值。

http://codepen.io/jimmykup/pen/exAip?editors=101 http://codepen.io/jimmykup/pen/exAip?editors=101

First I create my JSON object. 首先,我创建我的JSON对象。 In this case it only has two values. 在这种情况下,它只有两个值。 One name and one url . 一个name和一个url

var jsonObj = [];

var name = "1stname";
var url = "firsturl";

item = {}
item ["name"] = name;
item ["url"] = url;

jsonObj.push(item);

Next I use jQuery's .each() to find all inputs with a class of .name and I use the index to insert the value of "name" into the input. 接下来,我使用jQuery的.each()查找具有.name类的所有输入,并使用index将“ name”的值插入输入中。 After that I want to go through all of the inputs with .url as the class name and do the same. 之后,我要使用.url作为类名浏览所有输入,并执行相同的操作。

$("input.name").each(function( index ) {
    if ( jsonObj[index].name ) {
      $(this).val( jsonObj[index].name );
  }
});

$("input.url").each(function( index ) {
    if ( jsonObj[index].url ) {
      $(this).val( jsonObj[index].url );
  }
});

The problems is that if my JSON object has 1 value for "name" but .each() finds 2 inputs, once it gets to the second input I get this error in my console. 问题是,如果我的JSON对象的“名称”值为1,但是.each()找到2个输入,一旦到达第二个输入,我就会在控制台中收到此错误。

Uncaught TypeError: Cannot read property 'name' of undefined

Then my second .each() function fails to run. 然后,我的第二个.each()函数无法运行。 What can I do to avoid this issue? 我应该怎么做才能避免这个问题?

You need to make sure jsonObj[index] is defined before trying to get the name or url . 在尝试获取nameurl之前,需要确保定义了jsonObj[index]

$("input.name").each(function( index ) {
  var data = jsonObj[index];
  if ( data && data.name ) {
    $(this).val( data.name );
  }
});

$("input.url").each(function( index ) {
  var data = jsonObj[index];
  if ( data && data.url ) {
    $(this).val( data.url );
  }
});

Json objet is in this form:: Json objet的格式如下:

var jsonobj={"name":"1stname","url":"firsturl"};

with this format you can execute your code. 使用这种格式,您可以执行代码。

and what you are forming is basically an array. 而您所形成的基本上是一个数组。

Check that the index is less than the length of the array, otherwise quit the loop: 检查索引是否小于数组的长度,否则退出循环:

$("input.name").each(function( index ) {
  if (index < jsonObj.length && jsonObj[index].name ) {
    $(this).val( jsonObj[index].name );
  } else {
    return false;
  }
});

$("input.url").each(function( index ) {
  if ( index < jsonObj.length && jsonObj[index].url ) {
    $(this).val( jsonObj[index].name );
  } else {
    return false;
  }
});

Fork 叉子

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

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