其实我有这段 HTML 代码
<form method=POST action=dosomething.php>
<fieldset>
<legend>My account</legend>
<ul>
<li>
<label for=email>e-mail</label>
<span>
<?=$account->email?>
(<a name="change">change</a>)
</span>
<span name="ph">
<input id="email" name="email" placeholder="new email" type=email>
<br>
<button name="change_email">change</button> or <a name="cancel">undo</a>
</span>
</li>
<li>
<label for=foo>foo</label>
<span>
<?=$account->foo?>
(<a name="change">change</a>)
</span>
<span name="ph">
<input id="foo" name="foo" type=text>
<br>
<button name="change_foo">change</button> or <a name="cancel">undo</a>
</span>
</li>
</ul>
</fieldset>
</form>
我<li> ... </li>
只重复了 2 次部分,但它们重复了多次,你会注意到有一部分对所有人都是一样的。
我使用这个 JavaScript 是为了实现一个非常简单的事情:显示/隐藏两个<span>
s。
window.onload = function () {
/* email */
document.getElementsByName('change')[0].onclick = function () {
this.parentNode.style.display = 'none';
document.getElementsByName('ph')[0].style.display = 'block';
}
document.getElementsByName('cancel')[0].onclick = function () {
this.parentNode.style.display = 'none';
document.getElementsByName('change')[0].parentNode.style.display = 'block';
document.getElementsByName('change')[0].parentNode.style.width = '100%';
}
/* social id */
document.getElementsByName('change')[1].onclick = function () {
this.parentNode.style.display = 'none';
document.getElementsByName('ph')[1].style.display = 'block';
}
document.getElementsByName('cancel')[1].onclick = function () {
this.parentNode.style.display = 'none';
document.getElementsByName('change')[1].parentNode.style.display = 'block';
document.getElementsByName('change')[1].parentNode.style.width = '100%';
}
/* avatar */
document.getElementsByName('change')[2].onclick = function () {
this.parentNode.style.display = 'none';
document.getElementsByName('ph')[2].style.display = 'block';
}
document.getElementsByName('cancel')[2].onclick = function () {
this.parentNode.style.display = 'none';
document.getElementsByName('change')[2].parentNode.style.display = 'block';
document.getElementsByName('change')[2].parentNode.style.width = '100%';
}
/* shout */
document.getElementsByName('change')[3].onclick = function () {
this.parentNode.style.display = 'none';
document.getElementsByName('ph')[3].style.display = 'block';
}
document.getElementsByName('cancel')[3].onclick = function () {
this.parentNode.style.display = 'none';
document.getElementsByName('change')[3].parentNode.style.display = 'block';
document.getElementsByName('change')[3].parentNode.style.width = '100%';
}
}
这太长了……而且重复。如您所见,唯一改变的部分是getElementsByName('change')[aNumber]
.
我的问题是: 如何消除冗余?
一点说明:我想看看 jQuery 解决方案,但我更喜欢使用纯 JS。
先感谢您!