gpt4 book ai didi

javascript - JQUERY - 使用列表变量构建 HTML

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

如何使用列表变量创建构建 HTML...

这是我的代码错误...

html

<div class="demo">
<!-- append code -->
</div>

CSS

.demo_btn_btn1 {
color :red;
}

.demo_btn_btn2 {
color :blue;
}

.demo_btn_btn3 {
color :orange;
}

jQuery 代码

$(function(){
var cls = ['btn1','btn2','btn3'],
txt = ['button1','button2','button3'],
html = [];
html = $('<button class="demo_btn_' + cls + '"><span>' + txt + '</span></button>');
$(".demo").append(html);
});

输出我的代码

<div class="demo">
<button class="demo_btn_btn1,btn2,btn3">
<span>button1,button2,button3</span></button>
</div>

我想要这个...

<div class="demo">
<button class="demo_btn_btn1"><span>Button1</span></button>
<button class="demo_btn_btn2"><span>Button2</span></button>
<button class="demo_btn_btn3"><span>Button3</span></button>
</div>

请帮助我,提前谢谢

最佳答案

问题是,您将所有内容放在一个按钮中,这就是它显示为单个元素的原因。

您需要循环遍历这些内容并分配每个元素,如下所示。

$(function(){
var cls = ['btn1','btn2','btn3'],
txt = ['button1','button2','button3'],
html = [];
for (let i = 0; i < 3; i++)
{
html = $('<button class="demo_btn_' + cls[i] + '">' + txt[i] + '</button>');
$(".demo").append(html);
}

});
.demo_btn_btn1 {
color :red;
}

.demo_btn_btn2 {
color :blue;
}

.demo_btn_btn3 {
color :orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="demo">

</div>

关于javascript - JQUERY - 使用列表变量构建 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44611219/

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