document.getElementBy(id?) 取决于 html 中的输入.可点击的图库

document.getElementBy(id?) depending on the input in html. Clickable gallery

本文关键字:输入 html getElementBy id 取决于 document      更新时间:2023-09-26

最终目标是创建一个画廊(纯JS(。在此之前,我正在尝试一个模型。两个按钮,如果单击#1,则字符串1.jpg出现在下方,如果单击#2,则字符串2.jpg出现。我希望它在一个函数中工作。到目前为止,我拥有的:

Javascript:

var imageData = new Array (2);
imageData[0]="1.jpg";
imageData[1]="2.jpg";

function gallery() {
var answer = document.getElementById("what").value;
document.getElementById("show").innerText = imageData[answer];
}

.HTML:

    <button onclick="gallery()" id="what" value="1">1</button>
    <button onclick="gallery()" id="what" value="2">2</button>
    <div id="show"></div>

所以显然我不能有 2 个 id 命名为"什么"。
但是,如果我命名包含两个按钮的div,则没有任何反应,我尝试使用诸如:.classgetByName等,但不知何故它不起作用。我应该使用什么命令?我这样做是不是错了?我应该在 html 中创建某种数组吗?你是怎么做到的?

谢谢

您可以将this作为参数传递给函数,这会在您在 DOM 中单击的当前对象中传递什么。这样你甚至不需要使用id的:

<button onclick="gallery(this)" value="1">1</button>
<button onclick="gallery(this)" value="2">2</button>

然后在 JavaScript 中你可以说:

function gallery( item ) {
    var answer = item.value;
    ...
}