我建议:
function toggle(el, message1, message2) {
if (!el || !message1 || !message2) {
return false;
}
var text = el.tagName.toLowerCase() == 'input' ? el.value : (el.textContent || el.innerText),
newText = text == message1 ? message2 : message1;
if (el.tagName.toLowerCase() == 'input') {
el.value = newText;
}
else {
el.firstChild.nodeValue = newText;
}
}
document.getElementById('idButton').onclick = function(){
toggle(this, 'Show', "Don't show");
};
JS 小提琴演示。
以上内容稍作修改:
function isTag(el, tagname) {
if (!el || !tagname) {
return false;
}
else {
return el.tagName.toLowerCase() == tagname.toLowerCase() ? true : false;
}
}
function toggle(el, message1, message2) {
if (!el || !message1 || !message2) {
return false;
}
else {
var isInput = isTag(el, 'input'),
text = isInput ? el.value : el.textContent || el.innerText,
newText = text == message1 ? message2 : message1;
if (isInput) {
el.value = newText;
}
else if (el.textContent) {
el.textContent = newText;
}
else {
el.innerText = newText;
}
}
}
document.getElementById('idButton').onclick = function(){
toggle(this, 'Show', "Don't show");
};
JS 小提琴演示。