好的,我有一些 JS 通过 URL 从 JSON 中提取数据。 我知道想要将每个对象(作者名称、评级、作者网址)转换为 js ID,以便我可以在 html 中调用该 ID。
例如
<ul>
<li id=''></li>
<li id=''></li>
<li id=''></li>
</ul>
这是我到目前为止的 JS 代码
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=123-mg&libraries=places&callback=initMap"></script>
<script>
function initMap() {
var service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: '123'
}, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for(var i=0; i <= place.reviews.length; i++) {
console.log(place.reviews[i]);
alert(place.reviews[i].author_name);
alert(place.reviews[i].rating);
alert(place.reviews[i].author_url);
alert(place.reviews[i].text);
alert(place.reviews[i].relative_time_description);
alert(place.reviews[i].profile_photo_url);
}
}
});
}
</script>
将这些内容放入 html 中以便我可以在页面中设置样式和使用的最佳方法是什么?
最佳答案
您的 html 文件将如下所示:
<ul id="parent">
</ul>
将 jquery 脚本包含在 html 的 header 中。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
现在这是您想要的代码:
var child = someVariable; //Where somevariable is the variable you fetch from the url.
$("#parent").append('<li id="id_you_want_to_give">'+child+'</li>');
您为要附加的每个变量创建一个 li
标记,并将其附加到父级。
关于javascript - 将js对象转为html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40997076/