【问题标题】:How to display HTML of getElementsByClassName with JSON.parse() [duplicate]如何使用 JSON.parse() 显示 getElementsByClassName 的 HTML [重复]
【发布时间】:2021-10-03 21:44:49
【问题描述】:

如何调整此代码以显示值或 favFood?适用于 getElementById 但不适用于 getElementsByClassName 但我想使用一个类:

服务器文件 - ProcesssingFileOnServer.php:

<?php

$myObj = new stdClass();
$myObj->name = "John"; 
$myObj->favFood = "Pizza";

$myJSON = json_encode($myObj);

echo $myJSON;

?>

客户端文件:

<!DOCTYPE html>
<html>
<head>

</head>
<body>    

<p id="theName"></p>
<div class="bla"></div>

<script>    
const xmlhttp = new XMLHttpRequest();

xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);

  document.getElementById("theName").innerHTML = myObj.name;
  document.getElementsByClassName("bla") = myObj.favFood;
}
xmlhttp.open("GET", "ProcesssingFileOnServer.php");
xmlhttp.send();
</script>

</body>
</html>

【问题讨论】:

  • 你必须遍历.getElementsByClassName()返回的列表并单独对每个元素进行操作。
  • 你能给我一个迭代的例子吗?

标签: javascript php html json


【解决方案1】:

当他们使用类时,结果是一个数组。

var el = document.getElementsByClassName("bla")
for (let i = 0; i < el.length; i++) {
    el[i].innerHTML = 'asdsadas';
    
}

【讨论】:

  • 感谢作品。没有让的作品。这里是标准吗?
  • 可以,用es6没问题,可以用const
猜你喜欢
  • 1970-01-01
  • 2017-11-08
  • 2014-10-07
  • 1970-01-01
  • 2018-04-15
  • 1970-01-01
  • 2019-12-27
  • 1970-01-01
  • 2019-12-16
相关资源
最近更新 更多