这是我的第一个问题,我仍然是编程新手。 我发现了几乎相同的替代品,但我仍然无法使其正常工作。
我需要在管理页面中创建多个开/关按钮,可以在客户页面中创建活动(开启)或非活动(关闭)文章,将文本更改为开或关,并更改样式。当我使用getElementById获得1个按钮时它工作得很好,但是我尝试制作多个按钮并使用了getElementsByClassName,这一切都出错了。
以下是代码
<script type="text/javascript">
function onoff(){
var currentvalue = document.getElementById('onoff').value;
if(currentvalue == "Off"){
document.getElementById("onoff").value="On";
$("#onoff").addClass("on");
$("#onoff").removeClass("off");
}else{
document.getElementById("onoff").value="Off";
$("#onoff").addClass("off");
$("#onoff").removeClass("on");}}
</script>
<body onload="onoff();">
<input type="button" name="stat" value="On" id="onoff" onclick="onoff();" class="button-round blarge-round fright">
</body>
CSS:
<style type="text/css">
.button-round{
border: none;
border-radius: 30px;
margin-right: 10px;}
.on{
background-color: #914b38;
color: #000;
opacity: 0.8;
cursor: pointer;}
.off{
background-color: #1a1a1a;
color:#a2a1a1;
cursor: pointer;}
.blarge-round{
padding: 10px 8px;
font-size: 20px;}
.fright{float: right;}
</style>
真的需要帮助。这是我的任务。 谢谢你的帮助。
更新
以下是我使用getelementsbycalssname:
时的代码<script type="text/javascript">
function onoff(){
var currentvalue = document.getElementsByClassName("onoff").value;
for (var i = 0; i < currentvalue.length; i++) {
currentvalue[i];
if(currentvalue == "Off"){
document.getElementsByClassName("onoff").value="On";
$(this).addClass("on");
$(this).removeClass("off");
}else{
document.getElementsByClassName("onoff").value="Off";
$(this).addClass("off");
$(this).removeClass("on");
}
};
}
</script>
HTML:
<body onload="onoff();">
<input type="button" name="stat" value="On" onclick="onoff();" class="onoff button-round blarge-round fright">
<input type="button" name="stat" value="On" onclick="onoff();" class="onoff button-round blarge-round fright">
</body>
抱歉,如果错了。我还是新手。
答案 0 :(得分:1)
我建议,因为你已经在使用jQuery了:
function onoff(){
// 'this' is the clicked button,
// 'toLowerCase()' is to ensure case insensitivity:
var currentState = this.value.toLowerCase(),
// setting the new state (on/off) based on the
// current state:
newState = currentState === 'on' ? 'Off' : 'On';
// setting the value to the new state,
// toggling the class from on to off (or vice versa):
$(this).val(newState).toggleClass('on off');
}
// selecting all elements with the relevant class,
// binding a click handler to execute the function:
$('.onoff').click(onoff);
普通JavaScript替代方案(注意:此方法需要最新的浏览器):
// extending the prototype of HTMLInputElements, in order to allow chaining the method:
HTMLInputElement.prototype.toggle = function (states){
// setting defaults if alternative states aren't provided:
states = 'undefined' == typeof states ? ['on','off'] : states;
// retrieving the current state using 'toLowerCase()' for case-insensitivity:
var currentState = this.value.toLowerCase(),
// if the current state is the first state from the array we switch to
// the second, and vice-versa (again using toLowerCase() for case-insensitivity):
newState = currentState == states[0].toLowerCase() ? states[1] : states[0];
// updating the value:
this.value = newState;
// removing the currentState from the classList:
this.classList.remove(currentState);
// adding the newState to the classList:
this.classList.add(newState.toLowerCase());
}
// getting a nodeList/collection of all elements with the 'onoff' class-name:
var buttons = document.querySelectorAll('.onoff');
// iterating over that collection (using Array.prototype.forEach):
[].forEach.call(buttons, function(a){
// a is the specific element on this iteration,
// addEventListener binds a click-handler:
a.addEventListener('click', function(){
// a is still the same specific element, chaining the toggle method:
a.toggle();
});
});
最后,一个应该向后兼容并且与Internet Explorer兼容的版本(我认为):
function valueToggle(states, event) {
// defining the defaults for the states, if none are provided:
states = 'undefined' == typeof states ? ['on','off'] : states;
// defining the targeted element as the element that was clicked,
// the latter part (following '||') is for Internet Explorer:
var elem = event.target || window.event.srcElement,
// gets the current state:
currentState = elem.value.toLowerCase(),
// determines the new state:
newState = currentState == states[0].toLowerCase() ? states[1] : states[0],
// a string containing the current classes of the element:
curClasses = elem.className,
// a regular expression looking for a class-name equal to
// the current state surrounded by a word-break (spaces, punctuation, etc...):
reg = new RegExp("\\b" + currentState + "\\b");
// updating the value:
elem.value = newState;
// if the regular expression finds a match in the className string,
// we replace that occurrence with the new state, or if it's not found
// we add that new state/class (along with a space separator) to the classes:
elem.className = reg.test(curClasses) ? curClasses.replace(reg, newState.toLowerCase()) : curClasses + ' ' + newState.toLowerCase();
}
// gets elements of the 'onoff' class (this is not supported in early IE, though):
var buttons = document.getElementsByClassName('onoff');
// iterates over each of the elements in that returned nodeList:
for (var i = 0, len = buttons.length; i < len; i++){
// using 'onclick' (for backwards compatibility):
buttons[i].onclick = function(e){
// the 'e' is the event,
// calling the function:
valueToggle(['On','Off'], e);
};
}
请注意,在这种方法中,由于IE和其他浏览器之间的区别,处理事件对象似乎有必要确保将states
参数传递给函数(尽管这主要是因为我没有时间设置错误处理,如果它不存在,这将涉及检查Chrome,例如,传入的参数是一个事件而不是一个数组,我想)。
参考文献:
Array.prototype.forEach()
。document.querySelectorAll()
。document.getElementsByClassName()
。Element.classList
。Element.className
。EventTarget.addEventListener()
。Event.target
。Function.prototype.call()
。Node.nodeType
。RegExp.prototype.test()
。String.toLowerCase()
。typeof
。