gpt4 book ai didi

javascript - 使用 jQuery 我需要将此 JS 对象打印到 html

转载 作者:行者123 更新时间:2023-11-28 10:45:04 25 4
gpt4 key购买 nike

我需要在网页上显示按区域分隔的州列表。

我需要显示“西部”地区的标题,后跟显示为 <ul> 的州。 .

我确信有很多方法可以实现这一点,但我必须使用 jQuery。

var states = {  
"West":[
"Alaska",
"Arizona",
"California",
"Hawaii",
"Idaho",
"Nevada",
"Oregon",
"Utah",
"Washington"
],
"Central":[
"Colorado",
"Illinois",
"Indiana",
"Iowa",
"Kansas",
"Michigan",
"Minnesota",
"Missouri",
"Montana",
"Nebraska",
"New Mexico",
"North Dakota",
"Ohio",
"Oklahoma",
"South Dakota",
"Texas",
"Wisconsin",
"Wyoming"
],
"East":[
"Connecticut",
"Delaware",
"Kentucky",
"Maine",
"Maryland",
"Massachusetts",
"New Hampshire",
"New Jersey",
"New York",
"Pennsylvania",
"Rhode Island",
"Vermont",
"Virginia",
"West Virginia"
],
"South":[
"Alabama",
"Arkansas",
"Florida",
"Georgia",
"Louisiana",
"Mississippi",
"North Carolina",
"South Carolina",
"Tennessee"
]
};

这就是我到目前为止所做的:

var states = window.states;                                                         
var west = $.parseJSON( states ).West;

var $table = $('<table></table>');

for ( var i = 0; i < west.length; i++ ) {
var $line = $( "<tr></tr>" );
$line.append( $( "<td></td>" ).html( west ) );
$table.append( $line );`
}

$table.appendTo( '.west' );

最佳答案

使用for循环。例如,要显示每个区域的州,

var states = {  
"West":[
"Alaska",
"Arizona",
"California",
"Hawaii",
"Idaho",
"Nevada",
"Oregon",
"Utah",
"Washington"
],
"Central":[
"Colorado",
"Illinois",
"Indiana",
"Iowa",
"Kansas",
"Michigan",
"Minnesota",
"Missouri",
"Montana",
"Nebraska",
"New Mexico",
"North Dakota",
"Ohio",
"Oklahoma",
"South Dakota",
"Texas",
"Wisconsin",
"Wyoming"
],
"East":[
"Connecticut",
"Delaware",
"Kentucky",
"Maine",
"Maryland",
"Massachusetts",
"New Hampshire",
"New Jersey",
"New York",
"Pennsylvania",
"Rhode Island",
"Vermont",
"Virginia",
"West Virginia"
],
"South":[
"Alabama",
"Arkansas",
"Florida",
"Georgia",
"Louisiana",
"Mississippi",
"North Carolina",
"South Carolina",
"Tennessee"
]
};
var html = "<p>States by region</p>";
for (var region in states) {
html += "<ul>States in the " + region + " region: ";
for (var state in states[region]) {
html += "<li>" + states[region][state] + "</li>";
}
html += "</ul>";
}
$('#states').append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="states">

</div>

此代码允许您迭代每个区域及其子区域,而无需知道每个区域的定义。

编辑

  • 更改为迭代整个状态对象

关于javascript - 使用 jQuery 我需要将此 JS 对象打印到 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44786255/

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