2015-11-21 29 views
2

HTML如何從click事件對象屬性

<ol id="person-list"></ol> 
<div id="person"> 
    <h2 id="person-name"></h2> 
    <div id="person-age"></div> 
    <img id="person-address"> 
</div> 

JS

var persons = [{ 
    name: 'John', 
    age: 54, 
    address: '123 Main st.' 
}, { 
    name: 'Jack', 
    age: 55, 
    address: '456 Oak Ln.' 
}]; 


$('#person-list').on('click', 'li', function() { 
    alert('Hello'); // get other object info here? 
}); 

var f = function() { 
    for(var i = 0, len = persons.length; i < len; i++) { 
     $('#person-list').append('<li>' + persons[i].name + '</li>'); 
    } 
}; 
f(); 

當點擊一個人的名字,那就要抓住合適的對象的其他屬性並將其放置在適當的divs。例如,如果約翰被點擊,約翰的年齡和地址需要顯示在下面的div。我怎樣才能將列表中的人名與其他屬性值聯繫起來?我想在for循環中用每個名字保存「i」的值,所以有一個與每個名字相關的數字。然後以某種方式引用person [i] .age,當「i」值被點擊時,但聽起來很笨拙。

JSFIDDLE

+0

而不是Id使用類。 Id是唯一的 –

+0

@JqueryKing我沒有看到重複的ID。 – Tushar

回答

2

使用data-*屬性存儲在li索引。

  1. 使用data-indexli上創建並存儲在索引i
  2. 使用jQuery的data('index')來獲取點擊的元素
  3. 使用$(this)上保存的索引來訪問點擊的元素在事件處理程序

Demo

var persons = [{ 
 
    name: 'John', 
 
    age: 54, 
 
    address: '123 Main st.' 
 
}, { 
 
    name: 'Jack', 
 
    age: 55, 
 
    address: '456 Oak Ln.' 
 
}]; 
 

 

 
$('#person-list').on('click', 'li', function() { 
 
    // Get the clicked person's information 
 
    var person = persons[$(this).data('index')]; 
 

 
    // Set info in the corresponding elements 
 
    $('#person-name').html(person.name); 
 
    $('#person-age').html(person.age); 
 
    $('#person-address').html(person.address); 
 
}); 
 

 
var f = function() { 
 
    for (var i = 0, len = persons.length; i < len; i++) { 
 
    $('#person-list').append('<li data-index="' + i + '">' + persons[i].name + '</li>'); 
 
    //       ^^^^^^^^^^^^^^^^^^^^^^ 
 
    } 
 
}; 
 
f();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ol id="person-list"></ol> 
 
<div id="person"> 
 
    <h2 id="person-name"></h2> 
 

 
    <div id="person-age"></div> 
 
    <div id="person-address"></div> 
 
</div>

+1

非常感謝。所以我的想法有點正確。只是不知道如何實施。 data- *屬性看起來非常強大。 –

+0

歡迎@MatthewMoon。樂意效勞。 :) – Tushar

1

您可以添加一個data-attribute<li data-person="id_of_the_person">元素,它的單擊事件處理程序使用$(this).data("person")獲取,然後從列表中得到的人

1

您需要使用.index()函數來獲取索引名稱,然後使用該索引從persons數組中獲取名稱。像這樣:

$('#person-list').on('click', 'li', function() { 

    alert(persons[$(this).index()].name) 
}); 

這裏是更新的fiddle。從那裏,你可以做所有你需要的文本操作。

$('#person-name').html(persons[$(this).index()].name); 
$('#person-age').html(persons[$(this).index()].age); 
$('#person-address').html(persons[$(this).index()].address); 
1

在事件處理程序中,您可以訪問index(),然後您可以訪問相應的數據。

這裏是JSFiddle

+0

這似乎是最簡單的解決方案。 –

相關問題