如何使用JavaScript onclick函数和数组索引值

时间:2015-06-18 16:41:22

标签: javascript arrays dom user-input onclicklistener

我目前在JavaScript中使用onclick函数来显示存储在数组中的信息,具体取决于用户选择的元素。然后我需要另一个onclick函数,它允许我做同样的事情(根据选择显示内容),但基于所选的数组索引值。第一种方法很有效,因为用户选择基于ID。我没有成功使用第二种方法,因为我还没有想出如何根据数组索引值的选择显示内容。使用JavaScript是该项目的首选。

在选择一个专业(标记为生物学的元素)之后,用户将选择其中一个工作标题,说“bioArray [1] [2]中存储的”遗传顾问“,以及bioArray [4]和bioArray的innerHTML然后[5]将显示该职位所特有的薪资信息。我将要显示的信息将存储在每个职位的单独数组中 - 例如:geneticCounselor []

我的想法是通过使用嵌套数组我可能会找到一种方法,允许我显示基于索引值选择的内容。到目前为止,我已经看到了讨论事件冒泡和“这个”的方法,但不相信这些方法满足我的要求。

参见JS Bin Demo:http://jsbin.com/dolucowuwu/edit?html,css,js,output

CSS:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>

<style>

h4 {
    border: 1px solid black;
    border-radius: 8px;
    padding: 10px 2px 10px 2px;
    margin: 20px 20px 0px 20px;
    background-color: #F0F0F0;
    border-color: #F8F8F8;
    color: #505050;
    cursor: pointer;
}

.active {
    background-color: #99E6FF;
}

p {
    font-size: 1.3em;
}

</style>

HTML:

<div class="container contentContainer">
    <div id="pTwoRowOne">
        <div class="row">
            <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 row row-centered">
                <h4 id="bio" class="selected">Biology</h4>
            </div>
        </div>
    </div>
    <div id="pTwoRowTwo">
        <div class="row">
            <div class="row col-md-6">
                <h3 id="major" class="col-md-12 row row-centered">Select a major from above</h3>
                <h3 id="majorRep" class="col-md-12 row row-centered"></h3>
                    <p id="jobs" class="col-md-12 selectedTwo"></p>
                    <p id="skills"class="col-md-12"></p>
                    <p id="salaryRange" class="col-md-12"></p>
                    <p id="salaryRangeOC" class="col-md-12"></p>
                    <p id="salaryAvg" class="col-md-12"></p>
            </div>
        </div>
    </div>
</div>

JavaScript的:

var H4 = document.getElementsByClassName("selected"), act;

[].forEach.call(H4, function(el){
    el.addEventListener("click", function(){
       if(act) act.classList.remove("active");
       return (this.classList.toggle("active"), act=this);
    });
});

var bioArray = [
    "Biology",
    ['Common Job Titles: Biological/Lab Technician',' Medical and Health Services Manager',' Genetic Counselor'],
    "Skills in Demand: Relevant Certifications and Degree Programs Required",
    "Major Salary Range: $35,000 to $120,000 +",
    "Occupation Salary Range: Select a Job Title",
    "Average Salary: Select a Job Title"

];

    document.getElementById("bio").onclick=function() {
    document.getElementById("majorRep").innerHTML = bioArray[0];
    document.getElementById("jobs").innerHTML = bioArray[1];
    document.getElementById("skills").innerHTML = bioArray[2];
    document.getElementById("salaryRange").innerHTML = bioArray[3];
    document.getElementById("salaryRangeOC").innerHTML = bioArray[4];
    document.getElementById("salaryAvg").innerHTML = bioArray[5];
}

var geneticCounselor = [
    "Occupation Salary Range: $45,000 to $90,000",
    "Average Salary: $57,000"
];

3 个答案:

答案 0 :(得分:1)

我已经改变了您的大部分数据和网站,以创建一个更易于维护的示例:

  1. 我选择使用一个名为jquery的库,它可以在操作dom元素和绑定事件时为你提供很多帮助。
  2. 分析您的数据,删除可重复使用的单词到html,并使数据结构更有意义。
  3. 添加一些类来更轻松地控制/聆听目标事件。
  4. 以下是它的成果:

    &#13;
    &#13;
    // Reform of datastructure.
    var MainCategory = {
      'Biology': {
        'jobs': [' Biological/Lab Technician,', ' Medical and Health Services Manager,', ' Genetic Counselor'],
        'skills': 'Relevant Certifications and Degree Programs Required, Analysis, ANOVA, Attention to Detail, Analytical, Biological Data Collection, Data Entry, DNA Isolation/Sequencing',
        'salaryRange': '$335,000 to $120,000 +',
        'salary': '$35,000 to $120,000 +'
      },
    
      'Cartography': {
        'jobs': [' City Planner,', ' Natural Resource Manager,', ' Environmental Planner,', ' GIS Analyst,', ' GIS Specialist,', ' Cartographer'],
        'skills': 'Relevant Certifications and Degree Programs Required, ArcGIS Mapping Suite, Python Programming, Photogrammetry, Attention to Detail, Visual Basic/.NET',
        'salaryRange': '$40,000 to $115,000 +',
        'salary': '$35,000 to $120,000 +'
      }
    };
    
    var Jobs = {
      ' Biological/Lab Technician,': {
        'Salary': '$95,000 to $110,000',
        'AverageSalary': '$87,000'
      },
      ' Medical and Health Services Manager,': {
        'Salary': '$75,000 to $90,000',
        'AverageSalary': '$57,000'
      },
      ' Genetic Counselor': {
        'Salary': '$45,000 to $90,000',
        'AverageSalary': '$57,000'
      },
      ' City Planner,': {
        'Salary': '$775,000 to $90,000',
        'AverageSalary': '$57,000'
      }
    
    };
    
    // Get main element blocks
    var mainSelect = $('#mainSelect');
    var cart = $('#cart');
    var details = $('#details');
    
    
    // Put in main category info.
    $.each(MainCategory, function(key) {
      var option = $('<h4>');
      option.text(key).data('category', key).appendTo(mainSelect);
    })
    
    // Define event handler
    var showDetail = function(category) {
      var categoryData = MainCategory[category];
    
      // Do nothing if no detail info.
      if (typeof categoryData === 'undefined') {
        details.toggle(false);
        return;
      }
      details.toggle(true);
      // Put info to each detail element
      $.each(categoryData, function(key, value) {
        var info = details.find('#' + key);
        if (key === 'jobs') {
          // Create a selectable job list.
          info.children().remove();
          $.each(value, function(id, job) {
            var jobOption = $('<span>');
            jobOption.addClass('job').data('job', job).text(job).appendTo(info);
          });
        } else {
          info.find('span').text(value);
        }
    
      });
    
      // Set default display text for those job related info.
      details.find('.job-related span').text('Select a Job Title');
    };
    // 
    var showJobDetail = function(job) {
      var jobInfo = Jobs[job],
        jobSalary, jobAverageSalary;
      if (typeof jobInfo === 'undefined') {
        details.find('.job-related span').text('Select a Job Title');
      } else {
        jobSalary = jobInfo.Salary ? jobInfo.Salary : 'Lack of info.';
        jobAverageSalary = jobInfo.AverageSalary ? jobInfo.AverageSalary : 'Lack of info.'
        details.find('#jobSalary span').text(jobSalary);
        details.find('#jobAverageSalary span').text(jobAverageSalary);
      }
    }
    
    // Setup events.
    mainSelect.on('click', 'h4', function() {
      $(this).siblings('.active').removeClass('active');
      $(this).addClass('active');
      var category = $(this).data('category');
      showDetail(category);
    });
    // Bind events to job list.
    details.on('click', 'span.job', function() {
      var job = $(this).data('job');
      showJobDetail(job);
    });
    &#13;
    h4 {
      border: 1px solid black;
      border-radius: 8px;
      padding: 10px 2px 10px 2px;
      margin: 20px 20px 0px 20px;
      background-color: #F0F0F0;
      border-color: #F8F8F8;
      color: #505050;
      cursor: pointer;
    }
    .active {
      background-color: #99E6FF;
    }
    p {
      font-size: 1.3em;
    }
    .fontIncrease {
      font-size: 1.2em;
      margin-bottom: 10px;
    }
    .pointerClass:hover {
      cursor: pointer;
    }
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <div id="mainSelect" class="selected"></div>
    <div id="cart" class="selected"></div>
    <div id="details" style="display:none">
      <div id="jobs" class="fontIncrease  pointerClass">
        Related Job Titles: <span></span>
      </div>
      <div id="skills" class="fontIncrease">
        Skills in Demand: <span></span>
      </div>
      <div id="salaryRange" class="fontIncrease">
        Major Salary Range: <span></span>
      </div>
      <div id="jobSalary" class='job-related fontIncrease'>
        Occupation Salary Range: <span></span>
      </div>
      <div id="jobAverageSalary" class='job-related fontIncrease'>
        Average Salary: <span></span>
      </div>
    </div>
    &#13;
    &#13;
    &#13;

    如果您对代码有疑问,请随时提问!

答案 1 :(得分:0)

您的问题可以更好地解释,但我想我已经明白了。有很多方法可以达到你想要的效果,而且我没有理由认为你没有比你得到的更接近(除了懒惰= P)。

无论如何,让我试着帮助你。

您可以使用对象。他们会让你的生活更轻松。所以让我们为这些工作建立一个对象:

var jobs = {
    'geneticCounselor': {
        'jobName': 'Genetic Counselor',
        'occupationSalaryRange': '$45,000 to $90,000',
        'averageSalary': '$57,000'
    },
    'biologicalLabTechnician': {
        'jobName': 'Biological/Lab Technician',
        'occupationSalaryRange': '$00,000 to $00,000',
        'averageSalary': '$00,000'
    },
    //...Keep adding jobs
};

现在您可以控制要处理的信息。如果您不了解JS对象,我建议您阅读this article。现在让我们根据对象创建HTML:

document.getElementById("bio").addEventListener('click', function() {
  //Access each job in our object
  for (var key in jobs) {
    //get the job object reference
    var job = jobs[key];

    //Create a HTML element do display the information
    var p = document.createElement('p');

    //Creates a reference to keep track on our 'jobs' object
    p.setAttribute('data-job', key);

    //Set the text of the element
    p.textContent = job.jobName;

    //Add function to each job
    p.addEventListener('click', function() {
     //Retrieve the obj reference in the HTML element
     var dataJob = this.getAttribute('data-job');

     //Use the HTML element reference to get the OBJ reference, where the info is stored
     var job = jobs[dataJob];

     //Set the job info into the <p>
     document.getElementById('salaryRange').textContent = job.occupationSalaryRange;

     //Set the job info into the <p>
     document.getElementById('salaryAvg').textContent = job.averageSalary;
    });

    //Put the element on the page
    document.getElementById('jobs').appendChild(p);
}

所以我的完整JS是:

var H4 = document.getElementsByClassName("selected"), act;

[].forEach.call(H4, function(el){
    el.addEventListener("click", function(){
       if(act) act.classList.remove("active");
       return (this.classList.toggle("active"), act=this);
    });
});

var jobs = {
    'geneticCounselor': {
        'jobName': 'Genetic Counselor',
        'occupationSalaryRange': '$45,000 to $90,000',
        'averageSalary': '$57,000'
    },
    'biologicalLabTechnician': {
        'jobName': 'Biological/Lab Technician',
        'occupationSalaryRange': '$00,000 to $00,000',
        'averageSalary': '$00,000'
    }
};

document.getElementById("bio").addEventListener('click', function() {
  //Access each job in our object
  for (var key in jobs) {
    //get the job object reference
    var job = jobs[key];

    //Create a HTML element do display the information
    var p = document.createElement('p');

    //Creates a reference to keep track on our 'jobs' object
    p.setAttribute('data-job', key);

    //Set the text of the element
    p.textContent = job.jobName;

    //Add function to each job
    p.addEventListener('click', function() {
     //Retrieve the obj reference in the HTML element
     var dataJob = this.getAttribute('data-job');

     //Use the HTML element reference to get the OBJ reference, where the info is stored
     var job = jobs[dataJob];

    //Set the job info into the <p>
    document.getElementById('salaryRange').textContent = job.occupationSalaryRange;

    //Set the job info into the <p>
    document.getElementById('salaryAvg').textContent = job.averageSalary;
    });

    //Put the element on the page
    document.getElementById('jobs').appendChild(p);
}
});

请注意,还有其他方法(以及更好的方法)来实现这些类型的结果。您应该阅读一些关于使用JS进行HTML / DOM操作的内容以获得更好的知识。

答案 2 :(得分:0)

// Reform of datastructure.
var MainCategory = {
  'Biology': {
    'jobs': [' Biological/Lab Technician,', ' Medical and Health Services Manager,', ' Genetic Counselor'],
    'skills': 'Relevant Certifications and Degree Programs Required, Analysis, ANOVA, Attention to Detail, Analytical, Biological Data Collection, Data Entry, DNA Isolation/Sequencing',
    'salaryRange': '$335,000 to $120,000 +',
    'salary': '$35,000 to $120,000 +'
  },

  'Cartography': {
    'jobs': [' City Planner,', ' Natural Resource Manager,', ' Environmental Planner,', ' GIS Analyst,', ' GIS Specialist,', ' Cartographer'],
    'skills': 'Relevant Certifications and Degree Programs Required, ArcGIS Mapping Suite, Python Programming, Photogrammetry, Attention to Detail, Visual Basic/.NET',
    'salaryRange': '$40,000 to $115,000 +',
    'salary': '$35,000 to $120,000 +'
  }
};

var Jobs = {
  ' Biological/Lab Technician,': {
    'Salary': '$95,000 to $110,000',
    'AverageSalary': '$87,000'
  },
  ' Medical and Health Services Manager,': {
    'Salary': '$75,000 to $90,000',
    'AverageSalary': '$57,000'
  },
  ' Genetic Counselor': {
    'Salary': '$45,000 to $90,000',
    'AverageSalary': '$57,000'
  },
  ' City Planner,': {
    'Salary': '$775,000 to $90,000',
    'AverageSalary': '$57,000'
  }

};

// Get main element blocks
var mainSelect = $('#mainSelect');
var cart = $('#cart');
var details = $('#details');


// Put in main category info.
$.each(MainCategory, function(key) {
  var option = $('<h4>');
  option.text(key).data('category', key).appendTo(mainSelect);
})

// Define event handler
var showDetail = function(category) {
  var categoryData = MainCategory[category];

  // Do nothing if no detail info.
  if (typeof categoryData === 'undefined') {
    details.toggle(false);
    return;
  }
  details.toggle(true);
  // Put info to each detail element
  $.each(categoryData, function(key, value) {
    var info = details.find('#' + key);
    if (key === 'jobs') {
      // Create a selectable job list.
      info.children().remove();
      $.each(value, function(id, job) {
        var jobOption = $('<span>');
        jobOption.addClass('job').data('job', job).text(job).appendTo(info);
      });
    } else {
      info.find('span').text(value);
    }

  });

  // Set default display text for those job related info.
  details.find('.job-related span').text('Select a Job Title');
};
// 
var showJobDetail = function(job) {
  var jobInfo = Jobs[job],
    jobSalary, jobAverageSalary;
  if (typeof jobInfo === 'undefined') {
    details.find('.job-related span').text('Select a Job Title');
  } else {
    jobSalary = jobInfo.Salary ? jobInfo.Salary : 'Lack of info.';
    jobAverageSalary = jobInfo.AverageSalary ? jobInfo.AverageSalary : 'Lack of info.'
    details.find('#jobSalary span').text(jobSalary);
    details.find('#jobAverageSalary span').text(jobAverageSalary);
  }
}

// Setup events.
mainSelect.on('click', 'h4', function() {
  $(this).siblings('.active').removeClass('active');
  $(this).addClass('active');
  var category = $(this).data('category');
  showDetail(category);
});
// Bind events to job list.
details.on('click', 'span.job', function() {
  var job = $(this).data('job');
  showJobDetail(job);
});
h4 {
  border: 1px solid black;
  border-radius: 8px;
  padding: 10px 2px 10px 2px;
  margin: 20px 20px 0px 20px;
  background-color: #F0F0F0;
  border-color: #F8F8F8;
  color: #505050;
  cursor: pointer;
}
.active {
  background-color: #99E6FF;
}
p {
  font-size: 1.3em;
}
.fontIncrease {
  font-size: 1.2em;
  margin-bottom: 10px;
}
.pointerClass:hover {
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="mainSelect" class="selected"></div>
<div id="cart" class="selected"></div>
<div id="details" style="display:none">
  <div id="jobs" class="fontIncrease  pointerClass">
    Related Job Titles: <span></span>
  </div>
  <div id="skills" class="fontIncrease">
    Skills in Demand: <span></span>
  </div>
  <div id="salaryRange" class="fontIncrease">
    Major Salary Range: <span></span>
  </div>
  <div id="jobSalary" class='job-related fontIncrease'>
    Occupation Salary Range: <span></span>
  </div>
  <div id="jobAverageSalary" class='job-related fontIncrease'>
    Average Salary: <span></span>
  </div>
</div>