简单设置显示:无/阻止与javascript [英] Simple setting off display: none / block with javascript

查看:96
本文介绍了简单设置显示:无/阻止与javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

<table>
    <tr class="odd"><td>Entry 1</td></tr>
    <tr class="even clickable" onclick="showHide('sub2')"><td>> Entry 2</td></tr>
    <tr class="even" id="sub2">
        <td><ul><li>Information 1</li><li>Information 2</li></ul></td>
    </tr>
    <tr class="odd"><td>Entry 3</td></tr>
    <tr class="even"><td>Entry 4</td></tr>       
</table>

和以下js:

function showHide(id) {
    var el = document.getElementById(id);
    if( el && el.style.display == 'none')    
        el.style.display = 'block';
    else 
        el.style.display = 'none';
}

与此css:

tr.odd{
    background-color: #dedede;
}

tr.even{
    background-color: #7ea9ff;    
}

tr.clickable{
    cursor: pointer;
}

tr.clickable:hover{
    color: white;
}

tr[id^="sub"]{
    display: none;
}

有人可以告诉我,为什么它不工作?我试图显示/隐藏的id =sub2的行

Could someone please tell me, why it doesn't work? I'm trying to show / hide onclick the row with the id="sub2"

在jsfiddle中的示例

推荐答案

运行代码时打开调试控制台,并且您将收到消息ReferenceError:showHide is not defined。

Open your debug console when you run your code, and you will get the message "ReferenceError: showHide is not defined".

如果您将html和javascript放在文件中,并运行该特定问题已解决。它与jsfiddle进程源的顺序有关。

If you place your html and javascript inside a file and run that that particular issue is resolved. It has something to do with the order with which jsfiddle processes sources.

其次,你试图通过id获取一个元素,但是给它一个类名 - 没有意义。通过给元素id和使用它的工作原理。

Secondly, you are trying to get an element by id, but give it the class name - that does not make sense. By giving elements id's and using that it works.

但这是非常不方便,只是用来解释为什么它不工作。你最好用rQuery使用jQuery。

But this is very unwieldy, and just serves to explain why it did not work. You are better off using jQuery as raphael said.

编辑:用链接替换html

function showHide(id) {
    var el = document.getElementById(id);
    if( el && el.style.display == 'block')    
        el.style.display = 'none';
    else 
        el.style.display = 'block';
}

这篇关于简单设置显示:无/阻止与javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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