我对JavaScript真的很陌生,只是写了我的第一个脚本。脚本的目的是通过单击按钮在屏幕上切换div,同时将按钮上的文本从show更改为hide,这取决于div是否可见。
当我将一个按钮放在页面上时,一切正常。但是,当我在页面上添加第二个按钮时,第一个按钮仍然有效,但是第二个按钮不起作用。
如何添加多个按钮并使脚本在它们上面起作用?我需要按钮来生成隐藏/显示文本,并且我需要它在没有jquery的ie7 +中工作。
var show = "show";
var hide = "hide";
var selector = document.getElementById('toggleCost');
var optionA = document.createTextNode(show);
var optionB = document.createTextNode(hide);
var targetClassCost = document.querySelector('.cost');
// determines the text, inside the element
function textChange () {
if (targetClassCost.style.visibility === 'visible') {
selector.appendChild(optionB);
} else {
selector.appendChild(optionA);
}
}
// toggles the text of the button when clicked
function toggle() {
if (targetClassCost.style.visibility === 'visible') {
targetClassCost.style.visibility = 'hidden';
} else {
targetClassCost.style.visibility = 'visible';
}
if (selector.innerHTML === show) {
selector.innerHTML = hide;
} else {
selector.innerHTML = show;
}
}
// calls the function that changes the text inside the element and inserts taht text into the button
selector.onclick = function () {toggle()};
textChange();
这是小提琴:http :
//jsfiddle.net/dodey/Lexruaou/
任何帮助是极大的赞赏!
因此,此处的区别在于您可以抽象化该函数,以便可以将其应用于任何按钮以允许其切换可见性,并且每次通过传入元素来更改其文本时都可以对其进行更改。
问题在于,如果有多个按钮试图控制同一元素的可见性,则它们将不会“监听”可见性更改,而会将文本更改传播到它们。
我注意到您textChange()
确实具有仅用于设置按钮的初始文本值的功能,我们可以通过删除此功能并在html级别将默认按钮文本设置为html的方式来减少代码,以便您首次单击时就可以使用。
如果我们希望它尽可能地可扩展,那么让我们来看一下创建一个函数,该函数允许我们同时传递可点击的项目和通过点击处理程序的切换实现的项目。
var show = "show";
var hide = "hide";
var toggledSelectorClass = 'cost'; // class of element(s) to be hidden/shown
var togglerSelectorClass = 'toggleCost'; // class of element(s) to be clicked
function attachToggleVisibilityHandler(togglerClass, toggledClass){
// finds all elements with matching class
// note that getElementsByClassName is not supported in IE8
// http://caniuse.com/#feat=getelementsbyclassname
var togglers = document.getElementsByClassName(togglerClass);
var toggled = document.getElementsByClassName(toggledClass);
// assigns the click event handler to each button with matching class
for(var x = 0; x < togglers.length; x++){
togglers[x].onclick = function(){
toggleCostVisibility(togglers, toggled);
}
}
}
// toggles the visibility of the element(s)
function toggleVisibility(togglers, toggled) {
for(var x = 0; x < toggled.length; x++){
if (toggled[x].style.visibility === 'visible') {
toggled[x].style.visibility = 'hidden';
} else {
toggled[x].style.visibility = 'visible';
}
}
toggleTextOnMatchingClassNames(togglers);
}
// changes the text of all buttons with matching class
function toggleTextOnMatchingClassNames(togglers){
for(var x = 0; x < togglers.length; x++){
if (togglers[x].innerHTML === show) {
togglers[x].innerHTML = hide;
} else {
togglers[x].innerHTML = show;
}
}
}
attachToggleVisibilityHandler(togglerSelectorClass, toggledSelectorClass);
这实际上是使您可以拥有多个.cost
元素(“切换的”元素)和多个.toggleCost
元素(“切换的”元素),它们彼此保持同步。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句