我尝试使用 javascript 按钮更改图像和文本。我可以同时更改图像或文本,但不能同时更改两者。请帮忙。
这是我尝试过的
function myFunction(name) {
document.getElementById("2").innerHTML = "SDMC " + name;
}
<html>
<body>
<img class="img-1006" id="1" src="https://2.bp.blogspot.com/-lsb_v-7rE5c/XaSceQO2x9I/AAAAAAAAO5w/W-3M-Ccg6RYq73bBV7ihp7OdYzkNrIPmwCLcBGAsYHQ/s320/images%2B%25281%2529.png" style="height: 500px;" />
<h1 class="textblock-4" id="2"> MEMBER</h1>
<button class="btn-1" onclick="document.getElementById('1').src='https://2.bp.blogspot.com/-lsb_v-7rE5c/XaSceQO2x9I/AAAAAAAAO5w/W-3M-Ccg6RYq73bBV7ihp7OdYzkNrIPmwCLcBGAsYHQ/s320/images%2B%25281%2529.png' ">gggggggg </button> <button class="btn-1" onclick="myFunction('kkkkkkkkkk')">gggggggg </button>
<button class="btn-2" onclick="document.getElementById('1').src='https://1.bp.blogspot.com/-XvSuPCgIHrc/Xb67ueOGjeI/AAAAAAAAPL8/T4F2rs5nIkA1A_UIi7oBCvevmIl0g5pVQCLcBGAsYHQ/s1600/download.jpg'">computer</button> <button class="btn-2" onclick="myFunction('yyyyyyyyy')">computer</button>
</body>
</html>
最佳答案
调用两个函数只需使用分号将它们分开即可。例如:
function myFunction() {
setImage();
setCaption();
}
就您而言,这会稍微困难一些,因为您正在更新图像并需要将该 src 图像 URI 和标题存储在某处。
理想情况下,您要开始考虑分离内联 JS 和 HTML。 Separation of concerns很有用,因为它使编写、理解和维护代码变得更加容易。
在此示例中,我将 JS 从 HTML 中分离出来,使标记更易于阅读。有一个容器(更新的图像和标题将存放在其中)和几个由数据属性中的 id 标识的按钮(为了方便起见,我将它们称为“计算机”和“成员”)。
图像和标题信息现在存储在名为 dict
的 JS 对象中。它包含两个由键(“computer”和“member”)标识的对象,其中包含相应的数据。
元素被缓存,按钮被赋予点击监听器。单击它们时,它们会调用 swap
函数。
swap
从单击的按钮中获取 id,并用它调用 getHTML
以从字典对象中获取正确的容器 HTML。 HTML 以字符串形式返回,容器 HTML 随之更新。
// The dictionary is an object that contains
// objects for each img/caption type
const dict = {
member: {
img: 'https://2.bp.blogspot.com/-lsb_v-7rE5c/XaSceQO2x9I/AAAAAAAAO5w/W-3M-Ccg6RYq73bBV7ihp7OdYzkNrIPmwCLcBGAsYHQ/s320/images%2B%25281%2529.png',
caption: 'kkkkkkkkk'
},
computer: {
img: 'https://1.bp.blogspot.com/-XvSuPCgIHrc/Xb67ueOGjeI/AAAAAAAAPL8/T4F2rs5nIkA1A_UIi7oBCvevmIl0g5pVQCLcBGAsYHQ/s1600/download.jpg',
caption: 'yyyyyyyyy'
}
};
// Cache the container and buttons
const container = document.querySelector('.container');
const buttons = document.querySelectorAll('.button');
// Add click listeners to the buttons
buttons.forEach(button => button.addEventListener('click', swap, false));
// Grabs the img and caption information from the
// dictionary using the id, and return a template literal
// describing the HTML you want to display
function getHTML(id) {
const { [id]: { img, caption } } = dict;
return `<img src="${img}" /><h3>SDMC ${caption}</h3>`;
}
// Grab the id from the element and set the container
// HTML to the returned HTML string from `getHTML`
function swap() {
const { dataset: { id } } = this;
container.innerHTML = getHTML(id);
}
.container { margin-top: 1em; }
<html>
<body>
<button class="button" data-id="member">Member</button>
<button class="button" data-id="computer">Computer</button>
<div class="container"></div>
</body>
</html>
关于javascript - 如何用一个按钮调用两个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58680037/