0

我正在尝试使用 javascript 在段落中添加一个类。但它只会将类传递给错误的 id。我想更改更改, <p id="para" class="para" >NAV One</p> 但目前它只更改列表的背景。有任何想法吗 ?

function toggle_visibility(id) {
    var thelist = document.getElementsByClassName("alist");
    var para = document.getElementsByClassName("para");
    for (var i = 0; i < thelist.length; i++) {
        thelist[i].style.display = 'none';
    }
    var e = document.getElementById(id);
    var para = document.getElementById(id);
    if(e.style.display == 'block') {
        e.style.display = 'none';
    } else { 
        para.className += " " + 'active';
        e.style.display = 'block';
    }
}

JSfiddle。 http://jsfiddle.net/FqqhY/4/

4

1 回答 1

1

我想你希望你的切换功能看起来更像这样

function toggle_visibility(hyp, id) {

    // hide all lists
    var allLists = document.getElementsByClassName('alist');
    for (var i = 0; i < allLists.length; i++)
        allLists[i].style.display = 'none';

    // deactive all paragraphs
    var allParas = document.getElementsByClassName('para');
    for (var i = 0; i < allParas.length; i++)
        allParas[i].className = 'para';

    // select the clicked hyper link and its child paragraph
    var list = document.getElementById(id),
        para = hyp.getElementsByClassName('para')[0];

    // activate the current para and show the list
    para.className = 'para active';
    list.style.display = 'block';
}

您还需要this作为第一个参数传递给切换函数以及相应的列表 id

<a href="#" onclick="toggle_visibility(this, 'list1');">

小提琴

于 2013-04-22T15:21:06.870 回答