示例
假设我在javascript中有一系列学校对象......
schools =
[
{name: "School A", phone: "Phone A", location: "Location A"},
{name: "School B", phone: "Phone B", location: "Location B"},
{name: "School C", phone: "Phone C", location: "Location C"},
...
]
...我想在段落标签中显示学校名称......
<p data-name="School A">School A</p>
<p data-name="School B">School B</p>
<p data-name="School C">School C</p>
...当我点击给定的学校段落时,我想在单独的窗格中显示其他信息。例如,当我点击学校A ...
<div id="separate-pane">
<p>Phone A</p>
<p>Address A</p>
</div>
为此,我需要检索关联的对象,创建其他信息段落标记,并将它们附加到单独的窗格。如何以有效的方式单击给定的学校名称段落时,如何引用正确的javascript对象?
思想/思想
使用innerHTML
使用数据名称属性
这两种方法都应该有效,但有没有更好的方法来实现这一点,而无需迭代javascript数组来找到正确的对象? 此外,这个过程叫做我想要完成的是什么?
答案 0 :(得分:1)
我会将索引保存在HTML中的数据参数中,然后使用索引查找学校数组中的关联学校。简单代码:
<p data-name="School A" data-index="0">School A</p>
<p data-name="School B" data-index="1">School B</p>
<p data-name="School C" data-index="2">School C</p>
$(document).ready(function(){
var school = [
{name: "School A", phone: "Phone A", location: "Location A"},
{name: "School B", phone: "Phone B", location: "Location B"},
{name: "School C", phone: "Phone C", location: "Location C"},
...
]
$('.button').on('click', function(){
var index = $(this).data('index');
var data = school[index];
//Use the data to show the info.
});
})
答案 1 :(得分:1)
扩展Nicolas的答案,当您从schools
数组创建HTML时,可以将数组索引放入数据属性中:
$.each(schools, function(i, school) {
$("#links").append($("<p>", {
"class": "link",
text: school.name,
data: { index: i }
});
});
$(".link").click(function() {
var school = schools[$(this).data("index");
// display school information in #separate-pane
});
答案 2 :(得分:0)
如果在点击监听器上使用jquery,你可以使用$(this).data(&#34; name&#34;)来获取存储在data-name attriburw中的数据
答案 3 :(得分:0)
您可以使用jQuery p
功能将整个学校对象存储在创建的data
元素中,然后在元素单击时检索它,如下所示。查看演示 - Fiddle Demo
var schools = [
{name: "School A", phone: "Phone A", location: "Location A"},
{name: "School B", phone: "Phone B", location: "Location B"},
{name: "School C", phone: "Phone C", location: "Location C"}
]
schools.forEach(function(item){
var $el = $('<p>' + item.name + '</p>');
$.data($el[0], item); // store school object with the element
$el.click(function(){
$('#separate-pane').html( $.data(this, item).phone + ' '+ $.data(this, item).location ); // retrieve saved school object
})
$('#schools').append($el);
})