2015-10-21 21 views
0

我有一個有4個數組的對象,基本上告訴我有多少朋友住在不同的房間。我不希望爲4個不同的房間編寫相同的代碼,而是希望能夠根據用戶點擊的空間來選擇適當的數組。我想象使用這個,但我不確定這樣做的最佳方式。根據點擊的頁面從對象中選擇不同的陣列

因此,而不是創建4個不同的房間功能,我想選擇'這個'房間,然後運行該功能。

這是否有意義?

Student.friends = function(){ 
    var data = { 
    'delux': ["Bob Smith","Jane Doe", "Bubba Hyde","Betsy Toheavens"], 
    'shared': ['Bob Smith'], 
    'animal': ["Bob Smith", "Jane Doe","Bubba Hyde"], 
    'another': ["Bob Smith","Jane Doe"], 
    'and-another': [] 
    } 
    Student.delux(data) 
} 

Student.delux = function(data){ 
    var delux = data['delux'].sort() 

} 

回答

0

你可以用jQuery來做到這一點。將一個事件監聽器添加到您的每個房間,然後根據您房間的ID對陣列進行一些操作。

HTML:

<div id="delux" class="room"></div> 
<div id="shared" class="room"></div> 
<div id="animal" class="room"></div> 
<div id="another" class="room"></div> 
<p id="friends"></p> 

的Javascript:

var data = { 
    'delux': ["Bob Smith","Jane Doe", "Bubba Hyde","Betsy Toheavens"], 
    'shared': ['Bob Smith'], 
    'animal': ["Bob Smith", "Jane Doe","Bubba Hyde"], 
    'another': ["Bob Smith","Jane Doe"], 
    'and-another': [] 
    } 

// selects all DOM objects with the css class ".room" and 
// adds an event listener to those objects which fires when clicked 
$("body").on("click", ".room", function(){ 
    // you can then access your array with data[this.id], 
    // here I just display its content on the page 
    $("#friends").html(data[this.id].toString()); 
}); 

工作小提琴:https://jsfiddle.net/p6vur8oj/2/

相關問題