2015-06-18 72 views
-2

我目前在JavaScript中使用onclick函數來顯示存儲在數組中的信息,具體取決於用戶選擇哪個元素。然後我需要另一個onclick函數,它允許我做同樣的事情(基於選擇顯示內容),但是基於選擇的數組索引值。第一種方法效果很好,因爲用戶選擇基於ID。我還沒有成功的第二種方法,因爲我還沒有想出如何顯示基於選擇數組索引值的內容。對於這個項目,強烈推薦使用JavaScript。如何在數組索引值中使用JavaScript onclick函數

選擇一個專業(元素標記爲生物學)後,用戶將選擇其中一個職位名稱,如存儲在bioArray [1] [2]中的「Genetic Counselor」和bioArray的innerHTML [4]和然後bioArray [5]會顯示該職位唯一的工資信息。我將顯示的信息將存儲在每個職位的單獨陣列 - 例如:geneticCounselor []

我的想法是通過使用嵌套數組我可以找到一種方法,允許我顯示一旦選擇的內容是基於指數值。到目前爲止,我已經看到討論事件冒泡和「this」的方法,但不相信這些方法滿足我的要求。

見JS斌演示: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" 
]; 

回答

1

我已經改變了大部分數據和網站的創建更容易維護例如:操縱DOM元素時

  1. 我選擇使用一個名爲jQuery庫,它可以幫助你很多和事件綁定。
  2. 分析您的數據,將可重用的單詞移除到html,並使數據結構更有意義。
  3. 添加一些類來更容易地控制/收聽目標事件。

,下面將它變成:

// 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>

如果您對代碼的問題,隨便問!

+0

到目前爲止,這似乎運作良好,我可能有一些在完全實施的問題,但到目前爲止,一切順利。感謝您的幫助,因爲我被其他工作束縛了一下,所以我現在才能夠繼續! – Hambone

+0

很高興它解決了你的問題:)。 – fuyushimoya

+0

也許你可以在幾件事情上略見一斑,當多次選擇一個專業時,它會多次附加(我嘗試通過使用「.one」函數來解決這個問題,但這並不符合我的意圖)。同樣,當選擇一個新的專業時,它會追加上一份工作清單下面的工作清單,然後編譯成一個大清單,而不是替換以前的工作清單(我還嘗試使用「.replaceWith」解決了一個問題並創建了另一個清單)... I編輯你的作品,以反映我一直在忙着的工作,讓我知道你是否需要澄清 – Hambone

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操作的東西,以獲得更好的知識。

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>