-2

我需要让这个工作,我没有想法。我不能使用 jquery,它需要是纯 javascript/css。这有什么问题?

<a href="#id" onclick="toggle_visibility('id1', 'id2');">Change Payment Method</a>
<div id="id1"><p>test 1</p></div>
<div id="id2" style="display: none"><p>test 2</p></div>

function toggle_visibility(id1, id2) {  
var e = document.getElementById(id1);
var e2 = document.getElementById(id2);
if(e2.style.display == 'block') {                
  e.style.display = 'block';             
  e2.style.display = 'none';
}
else {
  e.style.display = 'none';            
  e2.style.display = 'block';
}              
} 
4

3 回答 3

2

您的代码示例的唯一问题是您没有将 javascript 包含在<script>标签中。

例子:

<a href="#id" onclick="toggle_visibility('id1', 'id2');">Change Payment Method</a>
<div id="id1"><p>test 1</p></div>
<div id="id2" style="display: none"><p>test 2</p></div>

<script type="text/javascript">
    function toggle_visibility(id1, id2) {  
        var e = document.getElementById(id1);
        var e2 = document.getElementById(id2);
        if(e2.style.display == 'block') {                
            e.style.display = 'block';             
            e2.style.display = 'none';
        }
        else {
            e.style.display = 'none';            
            e2.style.display = 'block';
        }              
    } 
</script>
于 2013-10-03T18:47:25.257 回答
1

它的工作原理!我在浏览器中尝试过

<html>
    <head>
        <title></title>
    </head>
    <body>
        <a href="#id" onclick="toggle_visibility('id1', 'id2');">Change Payment Method</a>
        <div id="id1"><p>test 1</p></div>
        <div id="id2" style="display: none"><p>test 2</p></div>

        <script type="text/javascript">
            function toggle_visibility(id1, id2) {  
                var e = document.getElementById(id1);
                var e2 = document.getElementById(id2);
                if(e2.style.display == 'block') {                
                    e.style.display = 'block';             
                    e2.style.display = 'none';
                 }
                 else {
                     e.style.display = 'none';            
                     e2.style.display = 'block';
                 }              
             }
         </script>
    </body>
</html>
于 2013-10-03T19:01:29.773 回答
0

内联样式是错误的形式,并且在语义上不正确。这应该通过 CSS 类更改来完成:

<a href="#id" onclick="toggle_visibility('id1', 'id2');">Change Payment Method</a>
<div id="id1" class="ClassThatShows"><p>test 1</p></div>
<div id="id2" class="ClassThatHides"><p>test 2</p></div>

<script type="text/javascript">
function toggle_visibility(hideMe, showMe) {  
    document.getElementById(hideMe).className = "ClassThatHides";
    document.getElementById(showMe).className = "ClassThatShows";
} 
</script>
于 2013-10-03T18:59:35.567 回答