使用 JavaScript 更改 <li> 的类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13783233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:45:56  来源:igfitidea点击:

Use JavaScript to change the class of an <li>

javascriptcsshtml-lists

提问by Benjamin

I have the following code:

我有以下代码:

<div id="nav">
  <ul>
    <li id="tabOne" class="first current"><a href="./CS1.html" target="SheetView">Page One</a></li>
    <li id="tabTwo"><a href="./CS2.html" target="SheetView">Page Two</a></li>
    <li id="tabThree"><a href="./CS3.html" target="SheetView">Page Three</li>
    <li id="tabFour"><a href="./CS4.html" target="SheetView">Page Four</a></li>
    <li id="tabFive"><a href="./CS5.html" target="SheetView">Page Five</a></li>
    <li id="tabSix"><a href="./CS6.html" target="SheetView">Page Six</a></li>
  </ul>

This loads the selected page into an iframe named "SheetView." What I need to do is use JavaScript to alter the class when an option that isn't the currently selected on is clicked. I should say that I have the current class already setup in my CSS. I just have no way to trigger it.

这会将所选页面加载到名为“SheetView”的 iframe 中。我需要做的是在单击当前未选中的选项时使用 JavaScript 更改类。我应该说我的 CSS 中已经设置了当前类。我只是没有办法触发它。

I thought adding an onlick event to the <UL>up there and calling onclick="Javascript:changeCurrent();"but there is the problem (four actually):

我想在上面添加一个 onlick 事件<UL>并调用onclick="Javascript:changeCurrent();"但存在问题(实际上是四个):

  1. Is <ul onclick="JavaScript:changeCurrent();>where I need to have the event?
  2. What is the resulting JavaScript to make the change happen?
  3. How can I cause the first option to be set as current by default?
  4. Is there a way to keep the currently selected option from being an active link?
  1. 就是<ul onclick="JavaScript:changeCurrent();>在那里,我需要有事件?
  2. 使更改发生的结果 JavaScript 是什么?
  3. 如何使第一个选项默认设置为当前选项?
  4. 有没有办法让当前选择的选项不成为活动链接?

I found a few different examples but I couldn't tailor them to work for me. Any help would be most appreciated.

我找到了一些不同的例子,但我无法定制它们来对我来说有效。非常感激任何的帮助。

采纳答案by joequincy

Since you specified that you wanted a non-jQuery response, here's a function that will toggle appropriately:

由于您指定需要非 jQuery 响应,因此这里有一个可以适当切换的函数:

function toggleNavSelected(el){
    var list = document.getElementById('nav').children[0];
    for(var i=0; i<list.children.length; i++){
        var cur = list.children[i];
        if(el==cur){
            cur.classList.add("current");
            cur.firstChild.onclick = (function(){
                toggleNavSelected(this.parentElement);
                return false;
            });
        } else {
            if(cur.classList.contains("current")){
                cur.classList.remove("current");
            }
            cur.firstChild.onclick = (function(){
                toggleNavSelected(this.parentElement);
            });
        }
    }
}

Either add an onclick handler to each LI (onclick="toggleNavSelected(this);") or execute the following after the menu has loaded:

向每个 LI ( onclick="toggleNavSelected(this);")添加一个 onclick 处理程序或在菜单加载后执行以下操作:

var list = document.getElementById('nav').children[0];
for(var i=0; i<list.children.length; i++){
    var el = list.children[i];
    el.firstChild.onclick = (function(){
        toggleNavSelected(this.parentElement);
    });
}

Demo: http://jsfiddle.net/bWY7P/2/

演示:http: //jsfiddle.net/bWY7P/2/

(note: The JSFiddle script has a small difference; it adds a return false;to the onclick function so that you can play with it without the links actually following the HREF attribute. Do not use that line in your live code)

(注意:JSFiddle 脚本有一个小的区别;它return false;向 onclick 函数添加了一个,这样您就可以在没有实际跟随 HREF 属性的链接的情况下使用它。不要在您的实时代码中使用该行)



Explanation:

解释:

The function looks at each LIelement within the #navelement.
If that element is the element passed to the function, then it adds the class .current.
Otherwise, it removes the class .current(if present).

该函数查看LI元素内的每个#nav元素。
如果该元素是传递给函数的元素,则它会添加 class .current
否则,它将删除该类.current(如果存在)。

The second part binds a function to the onclick event of each aelement that calls the toggleNavSelected()function and passes its parent element (the li) as the argument.

第二部分将函数绑定到a调用该toggleNavSelected()函数的每个元素的 onclick 事件,并将其父元素 (the li) 作为参数传递。

回答by Alexander North

1) if you want to change the currently selected class when you click an item, put the onclick into the li item 2) using jquery would be very easy here, all you have to do is import the jquery file with the <script>tag and you're ready! For example, you could do onclick="changeClass(this);"on the <li>tag and in a normal JavaScript file or in a script tag:

1) 如果您想在单击某个项目时更改当前选定的类,请将 onclick 放入 li 项目 2) 在这里使用 jquery 将非常容易,您只需导入带有<script>标签的 jquery 文件,然后您就可以了重新准备好!例如,您可以onclick="changeClass(this);"<li>标签和普通 JavaScript 文件或脚本标签中执行以下操作:

function changeClass(this){
 $('#nav li').attr("class","");
 $(this).attr("class","current");
}

Replace the 'current' with the class name you want to use

将“当前”替换为您要使用的类名

3) it should already be set as current

3)它应该已经被设置为当前

4) use the :visited CSS selector to change what colour followed links look like eg:

4) 使用 :visited CSS 选择器来改变跟随链接的颜色,例如:

a:visited{
 color: #000000;
}

回答by feeela

First of all you should set the event handler from a separate script, not from an onclickattribute. You don't repeat your code that way and have anything in one place. The HTML is also much cleaner.

首先,您应该从单独的脚本而不是从onclick属性设置事件处理程序。您不会以这种方式重复您的代码,而是将任何内容集中在一处。HTML 也更加简洁。

Using jQueryit would be as easy as:

使用jQuery就像这样简单:

var menuLinks = jQuery( '#nav a' );

menuLinks.on( 'click' function() {

    menuLinks.removeClass( 'active' );
    $( this ).addClass( 'active' );

} );

You could also do that in plain JS, but using some library keeps you out of the trouble of browser incompatibilities.

你也可以在普通的 JS 中做到这一点,但使用一些库可以让你摆脱浏览器不兼容的麻烦。