javascript改变一些类名 [英] javascript changes one some class names

查看:153
本文介绍了javascript改变一些类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的javascript函数只是改变了4个类中的两个。如果我再次点击它改变第三个,但完全忽略最后一个。

  function move(obj,obj2){
var _elements = document.getElementsByClassName(obj);
document.getElementsByClassName(obj2).className ='none';

for(var i = 0; i <_elements.length; i ++){
_elements [i] .className ='none';
}
}



 < a href =javascript:move('bigbox','bigbox_submit'); id =closebigbox>清除< / a> 

< form>
< input type =textclass =bigbox/>< br />
< input type =textclass =bigbox/>< Br />
< input type =textclass =bigbox/>< br />
< / form>
< a href =javascript:class =bigbox_submit>提交< / a>

如何使其停止执行并同时执行

$ b $ document.getElementsByClassName()返回 NodeList code>,这是一个活对象。也就是说,随着DOM的改变, NodeList 实例随之改变。因此,每次更改节点列表中某个元素的类时,该元素将从节点列表中删除,因为它不再匹配该类。您可以使用循环代替:

  var _elements = document。 getElementsByClassName(obj); 
while(_elements.length){
_elements [0] .className ='none';
}

第二个问题是你分配一个名为 className NodeList 对象。这不会影响 NodeList 对象中的任何元素。您需要设置 NodeList 中的元素的 className

  document.getElementsByClassName(obj2)[0] .className ='none'; 


my javascript function is only changing two of 4 classes. If I click it again it changes the third one but then completely ignores the last one.

function move(obj,obj2) {
    var _elements = document.getElementsByClassName(obj);
    document.getElementsByClassName(obj2).className = 'none';

    for( var i = 0; i < _elements.length; i ++){
        _elements[i].className ='none';
    }
}

<a href="javascript: move('bigbox','bigbox_submit');"  id="closebigbox" >Clear</a>

<form>
    <input type="text" class="bigbox" /><br/>
    <input type="text" class="bigbox" /><br/>
    <input type="text" class="bigbox" /><br/>
</form>
<a href="javascript:" class="bigbox_submit" >Submit</a>

How do I make it stop doing this and execute at the same time.

解决方案

The method document.getElementsByClassName() returns a NodeList, which is a "live" object. That is, as the DOM changes, the NodeList instance changes with it. So, each time you change the class of one of the elements in your node list, that element is then removed from the node list because it no longer matches the class. You can use a while loop instead:

var _elements = document.getElementsByClassName(obj);
while (_elements.length) {
    _elements[0].className ='none';
}

The second problem is that you are assigning a property named className to a NodeList object. This will not affect any of the elements in that NodeList object. You need to set the className of the elements in the NodeList.

document.getElementsByClassName(obj2)[0].className = 'none';

这篇关于javascript改变一些类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆