gpt4 book ai didi

javascript - 隐藏/显示元素和更改按钮

转载 作者:行者123 更新时间:2023-12-02 23:30:02 29 4
gpt4 key购买 nike

我想要一个按钮,单击时隐藏一个元素并显示另一个元素,并让按钮在单击时更改文本(我想我得到了这一部分)。另外,我想在加载页面时仅显示其中一个元素,并且单击按钮时仅显示另一个元素。我当前使用的代码几乎可以正确完成此操作,但是单击按钮后,会显示隐藏的元素(所需),但显示的其他元素不会隐藏。这是我的代码(我使用基本的 JS,我不想使用 jQuery)。

HTML

<html>
<body>
<div>
<span>E-Mail or Phone<br>
</span>
<button onclick="emph()" id="emphbtn" type="button">Use Phone</button>
</div>
<div id="phbox" style="display: none;">
<label for="phone">Phone</label><input id="phone" type="tel" />
</div>
<div id="embox">
<label for="mail">E-Mail</label><input id="mail">
</div>
</body>

和 JavaScript

function emph() {
// get the clock
var myPhone = document.getElementById('phbox');

// get the current value of the clock's display property
var displaySetting = myPhone.style.display;

// also get the clock button, so we can change what it says
var switchbtn = document.getElementById('emphbtn');

// now toggle the clock and the button text, depending on current state
if (displaySetting == 'block') {
// clock is visible. hide it
myPhone.style.display = 'none';
// change button text
switchbtn.innerHTML = 'Use Phone';
}
else {
// clock is hidden. show it
myPhone.style.display = 'block';
// change button text
switchbtn.innerHTML = 'Use Email';
}
}

最佳答案

您还需要切换电子邮件输入 embox

function emph() {
// get the clock
var myPhone = document.getElementById('phbox');
var myEmail = document.getElementById('embox');

// get the current value of the clock's display property
var displaySetting = myPhone.style.display;

// also get the clock button, so we can change what it says
var switchbtn = document.getElementById('emphbtn');

// now toggle the clock and the button text, depending on current state
if (displaySetting == 'block') {
// clock is visible. hide it
myPhone.style.display = 'none';
myEmail.style.display = 'block';
// change button text
switchbtn.innerHTML = 'Use Phone';
} else {
// clock is hidden. show it
myPhone.style.display = 'block';
myEmail.style.display = 'none';
// change button text
switchbtn.innerHTML = 'Use Email';
}
}
<div>
<span>E-Mail or Phone<br></span>
<button onclick="emph()" id="emphbtn" type="button">Use Phone</button>
</div>
<div id="phbox" style="display: none;">
<label for="phone">Phone</label><input id="phone" type="tel" />
</div>
<div id="embox">
<label for="mail">E-Mail</label><input id="mail">
</div>

关于javascript - 隐藏/显示元素和更改按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56553522/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com