如何使用 document.write 在 div 标签中获取 javascript 对象的输出?

How can i get the output of javascript object in div tag using document.write?

JavaScript 页数:

我创建了 javascript 函数,其中有一个名为 Passenger 的对象,它具有三个值,即 name="A"、age=30、reservationStatus=true。现在我想使用 document.write

在这三个 div 中打印这些值

HTML 页数:

我创建了三个 div 标签,id="name"、id="age"、id="reservationStatus" 和一个具有 [=34 的 onclick 事件的按钮=] 功能。

预期结果:

姓名:A 年龄:30 预订状态:true

使用document.getElementById() 来识别一个元素id(如div)并设置一个值作为

document.getElementById("name").innerHTML =Passenger.name;
document.getElementById("age").innerHTML =Passenger.age;
document.getElementById("reservationStatus").innerHTML =Passenger.reservationStatus;

const passenger = {
  name: 'A',
  age: 30,
  reservationStatus: true,
};

const button = document.querySelector('button');

const showInfo = () => {
  document.querySelector('#name').textContent = `Name: ${passenger.name}`;
  document.querySelector('#age').textContent = `Age: ${passenger.age}`;
  document.querySelector('#reservationStatus').textContent = `Reservation status: ${passenger.reservationStatus}`;
};

button.addEventListener('click', showInfo);
<button>Show</button>
<div id="name"></div>
<div id="age"></div>
<div id="reservationStatus"></div>

你可以这样试试:

window.onload = () => {

  const passenger = {
    name: 'A',
    age: 30,
    reservationStatus: true
  };

  const nameElement = document.querySelector('#name');
  const ageElement = document.querySelector('#age');
  const reservationStatusElement = document.querySelector('#reservationStatus');
  const btnShowPassengerElement = document.querySelector('#btnShowPassenger');

  // Hiding on window onload
  nameElement.innerHTML = '';
  ageElement.innerHTML = '';
  reservationStatusElement.innerHTML = '';

  btnShowPassengerElement.addEventListener('click', (event) => {

    // Showing them on click of the button
    nameElement.innerHTML = passenger.name;
    ageElement.innerHTML = passenger.age;
    reservationStatusElement.innerHTML = passenger.reservationStatus;
  });

};
group {
  display: inline-block;
  margin: 10px;
}
<button id="btnShowPassenger">Show Passenger Details </button>

<div>
  <div class="group">
    <div> Name: </div>
  </div>
  <div class="group">
    <div id="name"></div>
  </div>
</div>

<div>
  <div class="group">
    <div> Age: </div>
  </div>
  <div class="group">
    <div id="age"></div>
  </div>
</div>

<div>
  <div class="group">
    <div> Reservation Status: </div>
  </div>
  <div class="group">
    <div id="reservationStatus"></div>
  </div>
</div>