如何使用带有数组索引值的 JavaScript onclick 函数

How to use JavaScript onclick Functions with Array Index Values

我目前在 JavaScript 中使用 onclick 函数来显示存储在数组中的信息,具体取决于用户 select 在哪个元素上。然后我需要另一个 onclick 函数,它允许我做同样的事情(显示基于 selection 的内容)但基于 selected 的数组索引值。第一种方法效果很好,因为用户 selection 基于 ID。我没有成功使用第二种方法,因为我还没有弄清楚如何根据数组索引值的 selection 显示内容。此项目强烈推荐使用 JavaScript。

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

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

查看 JS Bin 演示: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: ,000 to 0,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: ,000 to ,000",
    "Average Salary: ,000"
];

你的问题可以得到更好的解释,但我想我明白你的意思了。有很多方法可以实现你想要的,我看不出你为什么不比你已经得到的更接近(除了懒惰=P)。

无论如何,让我尽力帮助你。

您可能正在处理对象。他们会让你的生活更轻松。因此,让我们为作业构建一个对象:

var jobs = {
    'geneticCounselor': {
        'jobName': 'Genetic Counselor',
        'occupationSalaryRange': ',000 to ,000',
        'averageSalary': ',000'
    },
    'biologicalLabTechnician': {
        'jobName': 'Biological/Lab Technician',
        'occupationSalaryRange': '[=10=],000 to [=10=],000',
        'averageSalary': '[=10=],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': ',000 to ,000',
        'averageSalary': ',000'
    },
    'biologicalLabTechnician': {
        'jobName': 'Biological/Lab Technician',
        'occupationSalaryRange': '[=12=],000 to [=12=],000',
        'averageSalary': '[=12=],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);
}
});

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

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

  1. 我选择使用一个名为 jquery 的库,它可以在操作 dom 元素和绑定事件时为您提供很多帮助。
  2. 分析您的数据,将可重复使用的词删除到 html,并使数据结构更有意义。
  3. 将一些 class 到 control/listen 添加到目标事件中更容易。

下面是它变成的样子:

// 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': '5,000 to 0,000 +',
    'salary': ',000 to 0,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': ',000 to 5,000 +',
    'salary': ',000 to 0,000 +'
  }
};

var Jobs = {
  ' Biological/Lab Technician,': {
    'Salary': ',000 to 0,000',
    'AverageSalary': ',000'
  },
  ' Medical and Health Services Manager,': {
    'Salary': ',000 to ,000',
    'AverageSalary': ',000'
  },
  ' Genetic Counselor': {
    'Salary': ',000 to ,000',
    'AverageSalary': ',000'
  },
  ' City Planner,': {
    'Salary': '5,000 to ,000',
    'AverageSalary': ',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>

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

// 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': '5,000 to 0,000 +',
    'salary': ',000 to 0,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': ',000 to 5,000 +',
    'salary': ',000 to 0,000 +'
  }
};

var Jobs = {
  ' Biological/Lab Technician,': {
    'Salary': ',000 to 0,000',
    'AverageSalary': ',000'
  },
  ' Medical and Health Services Manager,': {
    'Salary': ',000 to ,000',
    'AverageSalary': ',000'
  },
  ' Genetic Counselor': {
    'Salary': ',000 to ,000',
    'AverageSalary': ',000'
  },
  ' City Planner,': {
    'Salary': '5,000 to ,000',
    'AverageSalary': ',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>