我正在尝试创建一个包含3个JavaScript对象的网页

时间:2019-07-29 16:51:10

标签: javascript

<script>
// Create an object:
var person1 = {Title: "Title: A Song of Ice and Fire", Author: "Author: George RR Martin", Type:"Type: Paperback", Price:19.99};
var person2 = {Title:"Title: The Woman in the Window", Author:"Author: A.J. Finn", Type:"Type: Paperback", Price:6.29};
var person3 = {Title:"Title: The Silkworm", Author:"Author: Robert Galbraith", Type:"Type: Hardback", Price:14.99};

// Display some data from the object:
document.getElementById("demo1").innerHTML = person1.Title;
document.getElementById("demo2").innerHTML = person1.Author;
document.getElementById("demo3").innerHTML = person1.Type;
document.getElementById("demo4").innerHTML = person1.Price;

document.getElementById("code1").innerHTML = person2.Title;
document.getElementById("code2").innerHTML = person2.Author;
document.getElementById("code3").innerHTML = person2.Type;
document.getElementById("code4").innerHTML = person2.Price;

document.getElementById("job1").innerHTML = person3.Title;
document.getElementById("job2").innerHTML = person3.Author;
document.getElementById("job3").innerHTML = person3.Type;
document.getElementById("job4").innerHTML = person3.Price;
</script>
<html>
<body>

<h2>JavaScript Objects</h2>

<button onclick="show(0)">Book 1</button>
<button onclick="show(1)">Book 2</button>
<button onclick="show(2)">Book 3</button>

<h3>Book 1</h3>
<p id="demo1"></p>         
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>

<h3>Book 2</h3>
<p id="code1"></p>
<p id="code2"></p>
<p id="code3"></p>
<p id="code4"></p>

<h3>Book 3</h3>
<p id="job1"></p>
<p id="job2"></p>
<p id="job3"></p>
<p id="job4"></p>

</html>

<!-- begin snippet: js hide: false console: true babel: false -->

因此,基本上,我想要达到的目的是,当我单击书1,书2或书3的按钮时,例如,如果我单击书1的按钮书名,作者,类型,价格和图像将显示出来。我对此应该怎么做表示怀疑,并感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

尝试

let book1 = { title: "A Song of Ice and Fire", author: "George RR Martin", type: "Paperback", price: 19.99, image: "songoficeandfire.jpg" }
let book2 = { title: "The Woman in the Window", author: "A.J. Finn", type: "Paperback", price: 6.29, image: "womaninwindow.jpg"}
let book3 = { title: "The Silkworm", author: "Robert Galbraith", type: "Hardback", price: 14.99, image: "silkworm.jpg" }

let books = [book1, book2, book3];

function show(index) {
  msg.innerText = JSON.stringify(books[index], null, 4);
}
<button onclick="show(0)">Show book1</button>
<button onclick="show(1)">Show book2</button>
<button onclick="show(2)">Show book3</button>

<pre id="msg"></pre>