gpt4 book ai didi

javascript - 合并重复列表项并相应地更改 css

转载 作者:太空宇宙 更新时间:2023-11-04 12:40:32 25 4
gpt4 key购买 nike

假设我有这样的数组

myarray = ["apple","apple","apple","potato","apple",];

myarray = ["apple","apple","apple","potato","apple",];

function listCreate (data) {
var output='<ul>';
$.each(data,function(key,val){

output+='<li">';
output+='<h4 >'+ val +'</h4>';
output+='</li>';

});
output+='</ul>';
$('#mylist').html(output);
}
listCreate(myarray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mylist">
</div>

我用 jQuery 生成列表

我需要合并 n 个重复值并更改 li 高度 n*50px

示例

myarray = ["apple","apple","apple","potato","apple",];
<ul>

<li style="background:#A6445E; height:150px;";>apple</li>
<li style="background:#FFD433; height:50px;">potato</li>
<li style="background:#A6445E; height:50px;">apple</li>

</ul>

示例

myarray =["potato","volvo","volvo","potato","apple",];

<ul>

<li style="background:#A7777E; height:50px;";>potato</li>
<li style="background:#FFD433; height:100px;">volvo</li>
<li style="background:#A4565E; height:50px;">potato</li>
<li style="background:#A2125E; height:50px;">apple</li>

</ul>

最佳答案

只需使用原始数组创建一个新数组,但忽略紧随其后的重复项:

myarray = ["apple", "apple", "apple", "potato", "apple", "apple"];

var temp = myarray[0];
var fixedMyArray = [temp];
var myArrayCounter = [];
var counter = 1;
for (var i = 1; i < myarray.length; i++) {
if (temp != myarray[i]) {
temp = myarray[i];
fixedMyArray.push(temp);
myArrayCounter.push(counter);
counter = 1;
}
else
{
counter++;
}
}
myArrayCounter.push(counter);

function listCreate(data,dataCounter) {
var output = '<ul>';
var temp = 50;
for(var i = 0; i < data.length; i++)
{

output += '<li style="background:#A7777E; height:' + temp*dataCounter[i] + 'px;">';
output += '<h4 >' + data[i] + '</h4>';
output += '</li>';

}
output += '</ul>';
$('#mylist').html(output);



}
listCreate(fixedMyArray,myArrayCounter);

然后在您的函数中使用 fixedMyArraymyArrayCounter 而不是 myarray

listCreate(fixedMyArray,myArrayCounter);

这是 JSFiddle:http://jsfiddle.net/jpdjbcjt/1/

关于javascript - 合并重复列表项并相应地更改 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26914964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com