例如:
{
"data": [
{
"name": "grape",
"color": "purple"
},
{
"name": "apple",
"color": "green"
},
{
"name": "strawberry",
"color": "red"
}
]
}
我正在遍历数组:
for (var i=0; i < data.length; i++) {
var item = "<button>"+data[i].name+"</button>";
$('#items').append(item)
}
假设我想要它,因此当您单击按钮时,显示div
值中的color
,但对数组中的每个项目使用相同的div
。我该怎么办?
答案 0 :(得分:1)
向按钮添加事件处理程序。它在data
数组中搜索与按钮文本同名的对象,并显示颜色。
var data = [{
"name": "grape",
"color": "purple"
},
{
"name": "apple",
"color": "green"
},
{
"name": "strawberry",
"color": "red"
}
];
for (var i = 0; i < data.length; i++) {
var item = "<button data-color=" + data[i].color + ">" + data[i].name + "</button>";
$('#items').append(item)
}
$("button").click(function() {
var name = $(this).text();
var obj = data.find(el => el.name == name);
$("#outputdiv").text(obj.color);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="items"></div>
<div id="outputdiv"></div>
答案 1 :(得分:0)
您可以在创建每个按钮时将click
事件处理程序附加到每个按钮上,这样,当单击该按钮时,事件处理程序将使用指定的项格式化目标<div>
。
这是一个快速演示:
const data = [{
"name": "grape",
"color": "purple"
},
{
"name": "apple",
"color": "green"
},
{
"name": "strawberry",
"color": "red"
}
];
const displayDatum = (datum) => (event) =>
$('#output').css({ background: datum.color }).text(datum.name);
for (var i = 0; i < data.length; i++) {
var item = $('<button>').text(data[i].name);
item.click(displayDatum(data[i]));
$('#items').append(item);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="items" />
<div id="output" />
答案 2 :(得分:0)
var data = [
{
"name": "grape",
"color": "purple"
},
{
"name": "apple",
"color": "green"
},
{
"name": "strawberry",
"color": "red"
}
];
for (var i=0; i < data.length; i++) {
var item = "<button data-color="+data[i].color+">"+data[i].name+"</button>";
$('#items').append(item)
}
$( "button" ).click(function() {
$("#output" ).css('background', $(this).attr("data-color"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="items" />
<div id="output" style="width:100%; height:20px"/>
答案 3 :(得分:0)
您可以使用纯js
let d={"data":[{"name":"grape","color":"purple"},
{"name":"apple","color":"green"},{"name":"strawberry","color":"red"}]}
let b= (i) => {
box.style.background=d.data[i].color;
box.innerText = d.data[i].name;
}
d.data.map((x,i)=>btns.innerHTML+=`<button onclick="b(${i})">${x.name}</button>`)
#box { margin:10px; width:99px; height:99px; color:#fff; transition:1s }
<div id="btns"></div>
<div id="box"></div>