我希望有一个按钮,当单击该按钮时,它隐藏一个元素并显示另一个元素,并且希望按钮在单击时更改文本(我想我知道了这一部分)。另外,我只想在加载页面时显示一个元素,而当单击按钮时,仅显示另一个元素。我当前使用的代码几乎可以正确完成此操作,但是单击按钮后,将显示(希望)隐藏的元素,但未隐藏其他显示的元素。这是我的代码(我正在使用基本的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';
}
}
答案 0 :(得分:1)
您还需要切换电子邮件输入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>