我应该使用什么而不是 document.getElementById 来工作

What should i Use instead of document.getElementById for this to work

您好,我的 javascript 有问题。有人已经告诉我不要在我的代码中使用 document.getElementById 但我应该使用什么来代替它才能正常工作,我是否也应该在我的代码中更改其他内容?

我正在制作一个网站,用户可以将 post 上传到该网站。

            echo '<a class="annons-tb">
              <div style="background-image: url(img/gallery/'.$row["imgFullNameGallery"].');"></div>
              <h3>'.$row["titleGallery"].'</h3>
              <p>'.$row["descGallery"].'</p>
                <input type="button" class="button1" name="id" value="Visa Mer Info" onclick="on()"></a>
              <div id="overlay" onclick="off()">
              <div id="text">
              <img src="data:img/gallery/jpeg;base64,'.base64_encode($row["imgFullNameGallery"]).'" width="250" height="250">
              <h3>'.$row["titleGallery"].'</h3>
              <p1>Beskrivning: '.$row["descGallery"].'</p1>
              <div id=p-delen">
              <br />
              <p>Pris: '.$row["prisGallery"].'</p>
              <p>Namn: '.$row["namnGallery"].'</p>
              <p>Mail: '.$row["emailGallery"].'</p>
              <p>TelefonNummer: '.$row["nummerGallery"].'</p>
              </div>
              </div></div><script>
                function on() {
                  document.getElementById("overlay").style.display = "block";
                }

                function off() {
                  document.getElementById("overlay").style.display = "none";
                }
                </script>';

        }
    }
    ?>
      </div>

我已经做了一个叠加效果,所以当你点击一个按钮时,你可以查看更多关于 post 的信息,但现在当你按下按钮时,它总是显示第一个 [=] 的额外信息20=].

如果您为两种类型的元素(input[type='button']div)分配了一个事件侦听器但删除了 ID 属性 - 例如用相同值的 class 替换然后您可以像这样轻松监控 any/all 触发的事件。

<script>
    document.addEventListener('DOMContentLoaded',()=>{
        Array.prototype.slice.call( document.querySelectorAll( 'div.overlay, button.button1' ) ).forEach( function(node){
            node.addEventListener('click', function(e){
                e.preventDefault();
                switch( this.tagName ){
                    case 'INPUT':
                        this.style.display='block';
                    break;
                    case 'DIV':
                        this.style.display='none';
                    break;
                }
            });
        });
    });
</script>

以上使用 forEach 方法遍历使用 document.querySelectorAll 找到的节点集合 - 但是某些浏览器不支持在 nodelist 上使用此方法,因此使用Array.prototype.slice.call 将节点列表转换为数组。

支持的 HTML/PHP(基本相同,但 ID 属性已更改 classes 并且已正确缩进)

    echo '
        <a class="annons-tb">
            <div style="background-image: url(img/gallery/'.$row["imgFullNameGallery"].');"></div>
            <h3>'.$row["titleGallery"].'</h3>
            <p>'.$row["descGallery"].'</p>
            <input type="button" class="button1" name="id" value="Visa Mer Info">
        </a>
        <div class="overlay">
            <div class="text">
                <img src="data:img/gallery/jpeg;base64,'.base64_encode($row["imgFullNameGallery"]).'" width="250" height="250" />
                <h3>'.$row["titleGallery"].'</h3>
                <p1>Beskrivning: '.$row["descGallery"].'</p1>
                <div class="p-delen">
                    <br />
                    <p>Pris: '.$row["prisGallery"].'</p>
                    <p>Namn: '.$row["namnGallery"].'</p>
                    <p>Mail: '.$row["emailGallery"].'</p>
                    <p>TelefonNummer: '.$row["nummerGallery"].'</p>
                </div>
            </div>
        </div>';
    }
}
?>
  </div>

我对以上内容进行了一些更正(编写时未经过测试 - 抱歉)并制作了一个演示。您会注意到 javascript 出现在 HTML 主体之前 - 事件侦听器被注册是因为事件侦听器已经分配给主体,它实际上等待所有 DOM 元素被注册在尝试绑定到特定元素之前呈现。本质上你可以这样做或者在重复的内容之后

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8' />
        <title>Alternative for document.getElementById</title>
        <script>
            /*
                I had made a slight error with the selector - it should be input.button1
                rather than button.button1

                The action invoked by the button also needed to be changed - it now
                navigates up the DOM tree to it's parent then to the parent's sibling
            */
            document.addEventListener('DOMContentLoaded',()=>{
                Array.prototype.slice.call( document.querySelectorAll( 'div.overlay, input.button1' ) ).forEach( function(node){
                    node.addEventListener('click', function(e){
                        e.preventDefault();
                        switch( this.tagName ){
                            case 'INPUT':
                                this.parentNode.nextElementSibling.style.display='block';
                            break;
                            case 'DIV':
                                this.style.display='none';
                            break;
                        }
                    });
                });
            });
        </script>
        <style>
            html *{box-sizing:border-box;}
            #wrapper{width:100%;height:100vh;margin:0;padding:0;}
            #wrapper > a.annons-tb{ padding:1rem;height:5rem;width:100%;display:inline-block; }
            #wrapper > div.overlay{ background:whitesmoke;border:1px dotted rgba(100,100,100,0.25);padding:1rem;margin:1rem auto;display:none }
        </style>
    </head>
    <body>
        <div id='wrapper'>
        <?php
            /*
                To emulate the db call
                a static array can be used
            */
            $rs=array(
                array(
                    'titleGallery'=>'Mega Gallery 1',
                    'descGallery'=>'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed orci ipsum, commodo pulvinar rutrum non, congue ut justo. Phasellus nec scelerisque diam, ut cursus felis.',
                    'imgFullNameGallery'=>'Gallery 1',
                    'prisGallery'=>'abc',
                    'namnGallery'=>'bob',
                    'emailGallery'=>'gal1@example.com',
                    'nummerGallery'=>'0141 353 3780'
                ),
                array(
                    'titleGallery'=>'Super Gallery 2',
                    'descGallery'=>'urabitur tristique libero non lorem blandit eleifend. Sed gravida ut purus vitae dignissim. Aenean pellentesque, diam ac euismod eleifend, lorem mauris dapibus lorem, id fermentum augue nisi at nisl.',
                    'imgFullNameGallery'=>'Gallery 2',
                    'prisGallery'=>'def',
                    'namnGallery'=>'rita',
                    'emailGallery'=>'gal2@example.com',
                    'nummerGallery'=>'0131 551 7488'
                ),
                array(
                    'titleGallery'=>'Awesome Gallery 3',
                    'descGallery'=>'Morbi ultrices nisl elementum augue sagittis porttitor. Nulla posuere molestie quam posuere tempus. Sed convallis metus mi, quis faucibus est lobortis sed.',
                    'imgFullNameGallery'=>'Gallery 3',
                    'prisGallery'=>'ghi',
                    'namnGallery'=>'sue',
                    'emailGallery'=>'gal3@example.com',
                    'nummerGallery'=>'01307 462 059'
                )
            );
            /*
                for the static array a foreach rather than while loop
                but essentially the same...

                I prefer use printf to constantly escaping out from the html to
                include the variable but again essentially the same as the original
                except for the lack of ID attributes
            */
            foreach( $rs as $row ){
                printf('
                    <a class="annons-tb">
                        <div style="background-image: url(img/gallery/%s);"></div>
                        <h3>%s</h3>
                        <p>%s</p>
                        <input type="button" class="button1" name="id" value="Visa Mer Info">
                    </a>
                    <div class="overlay">
                        <div class="text">
                            <img src="data:img/gallery/jpeg;base64,%s" width="250" height="250" />
                            <h3>%s</h3>
                            <p1>Beskrivning: %s</p1>
                            <div class="p-delen">
                                <br />
                                <p>Pris: %s</p>
                                <p>Namn: %s</p>
                                <p>Mail: %s</p>
                                <p>TelefonNummer: %s</p>
                            </div>
                        </div>
                    </div>',

                    $row['imgFullNameGallery'],
                    $row['titleGallery'],
                    $row['descGallery'],
                    $row['imgFullNameGallery'],
                    $row['titleGallery'],
                    $row['descGallery'],
                    $row['prisGallery'],
                    $row['namnGallery'],
                    $row['emailGallery'],
                    $row['nummerGallery']
                );
            }

        ?>
        </div>
    </body>
</html>