因此,我正在大学进行有关DOM操作的基本任务。
基本上,我在HTML页面上有用户个人资料,并且有2个单选框-解锁和锁定。因此,当您切换“解锁”并单击“显示更多”按钮时,它将显示该配置文件的数据,并将按钮的名称更改为“隐藏”。问题是我单击“显示更多”,然后单击“隐藏”,然后当我再次单击“显示更多”时,它不起作用。就像整个事件侦听器停止工作一样。
function lockedProfile() {
const $buttons = document.getElementsByTagName('button');
Array.from($buttons).forEach(button => {
button.addEventListener('click', e => {
const parent = e.currentTarget.parentNode;
const checkBox = parent.children[4];
if (checkBox.checked) {
parent.children[9].style.display = 'block';
parent.children[10].textContent = 'Hide it';
button.addEventListener('click', () => {
if (checkBox.checked) {
parent.children[10].textContent = 'Show More';
parent.children[9].style.display = 'none';
}
});
}
});
});
}
我不知道HTML代码的相关性,但是如果您要检查它,就在这里:
谢谢!
答案 0 :(得分:0)
跟随方式
const allForms = document.querySelectorAll('form.profile')
;
allForms.forEach(f=>
{
f.onsubmit=e=>e.preventDefault() // disable forms submit
;
f.oninput=e=>
{
if (e.target.name === 'userLocked')
{
f.theButton.textContent = ( f.userLocked.value==='lock' ) ? 'Show More' : 'Hide it'
}
}
})
.profile {
display: block;
background-color: #e29fc1;
margin: 2em 1em;
}
<form class="profile">
my radio button 1
<p>
<label> <input type="radio" name="userLocked" value="lock" checked> Lock </label>
<label> <input type="radio" name="userLocked" value="unlock" > Unlock </label>
</p>
<button name="theButton">Show more</button>
</form>
<form class="profile">
my radio button 2
<p>
<label> <input type="radio" name="userLocked" value="lock" checked> Lock </label>
<label> <input type="radio" name="userLocked" value="unlock" > Unlock </label>
</p>
<button name="theButton">Show more</button>
</form>
<form class="profile">
my radio button 3
<p>
<label> <input type="radio" name="userLocked" value="lock" checked> Lock </label>
<label> <input type="radio" name="userLocked" value="unlock" > Unlock </label>
</p>
<button name="theButton">Show more</button>
</form>