Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 根据单击的页面从对象的不同数组中进行选择_Javascript_Jquery - Fatal编程技术网

Javascript 根据单击的页面从对象的不同数组中进行选择

Javascript 根据单击的页面从对象的不同数组中进行选择,javascript,jquery,Javascript,Jquery,我有一个对象,它有4个数组,基本上告诉我有多少朋友住在不同的房间。我不想为4个不同的房间编写相同的代码,而是希望能够根据用户单击的房间选择适当的数组。我想用这个,但我不确定最好的方法 因此,我不想为房间创建4个不同的功能,而是选择“this”房间,然后运行该功能 这有意义吗 Student.friends = function(){ var data = { 'delux': ["Bob Smith","Jane Doe", "Bubba Hyde","Betsy Toheavens

我有一个对象,它有4个数组,基本上告诉我有多少朋友住在不同的房间。我不想为4个不同的房间编写相同的代码,而是希望能够根据用户单击的房间选择适当的数组。我想用这个,但我不确定最好的方法

因此,我不想为房间创建4个不同的功能,而是选择“this”房间,然后运行该功能

这有意义吗

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() 

} 

您可以使用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>
  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());
});