从函数jquery调用数组

时间:2017-09-01 16:52:29

标签: javascript jquery arrays

我在jQuery中存储了一些数据。我想从带有函数的数组中调用它,但是当我调用数组时它不会返回任何值。我的 JSFiddle

jQuery代码

$('button').click(showInfo);

function showInfo(){
    var data = $(this).attr("dataid");
  //alert(data);
  dataArray(data);
  writeData(data);
}

function dataArray(call){
    var person1 = [{
        'name':'First Name',
        'position':'Director'
    }];
    var person1 = [{
        'name':'Second Name',
        'position':'Director'
    }];
}

function writeData(called){
    $('.person').removeClass('hidden');
  dataArray(called[0]);
  // write in divs
  $('.person .name').text(dataArray(called['name']));
  $('.person .position').text(dataArray(called['position']));
}

2 个答案:

答案 0 :(得分:1)

您需要从dataWrite调用中返回一些内容。在这种情况下,具有人物数据的对象的对象。然后你可以通过传入的名称对其进行过滤。

$('button').click(showInfo);

function showInfo() {
  var data = $(this).attr("dataid");
  //alert(data);
  writeData(data);
}

function dataArray() {
  var persons = {
    person1: {
      name: 'First Name',
      position: 'Director'
    },
    person2: {
      name: 'Second Name',
      position: 'Director'
    }
  };
  return persons;
}

function writeData(called) {
  $('.person').removeClass('hidden');
  //alert(called);
  // write in divs
  $('.person .name').text(dataArray()[called].name);
  $('.person .position').text(dataArray()[called].position);
}
.hidden {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button dataid="person1">Call person 1</button>

<button dataid="person2">Call person 2</button>
<br/>
<br/>
<div class="person hidden">
  <span>Name: </span>
  <div class="name"></div>
  <br/>
  <span>Position: </span>
  <div class="position"></div>
</div>

答案 1 :(得分:0)

您的代码中存在两个问题:

  1. dataArray函数未返回任何内容,因此您需要将其更改为:

    function dataArray(call){
     return {
      person1 :{
          name:'First Name',
          position:'Director'
      },
      person1 :{
        name:'Second Name',
            position:'Director'
       }
     }[call];
    }
    
  2. 您需要访问返回对象的密钥,即:

    $('.person .name').text(dataArray(called)['name']);
    $('.person .position').text(dataArray(called)['position']);
    
  3. 这是工作fiddle