首页 > 解决方案 > 如何通过id选择要显示的div?

问题描述

我有这样写的代码。我希望在单击带有“HELLO”引用的第一部分时显示 myDIV1,并在单击第二部分“HI”时显示 myDIV2。尝试使用 event.target 将 javascript var X 更改为 myDIV1 或 myDIV2 但不确定我使用的语法是否正确或我尝试的逻辑是否可行。

当点击第一部分或第二部分时,我想更改 var x = document.getElementbyId( '这里的两个 div' )。(抱歉语法不好)

html

<section class="news"> HELLO
</section>

<section class="news"> HI
</section>

<div class="divelement "id="myDIV1">
    This is my DIV1 element.
</div>

<div class="divelement "id="myDIV2">
    This is my DIV2 element.

javascript

 <script>
function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.style.display === "none") {
        x.style.display = "block";
        y.style.display = "block";
        } else {
        x.style.display = "none";
        y.style.display = "none";
    }
}
</script>

标签: javascripthtml

解决方案


你可以通过这种方式使用 jQuery 来做到这一点。

jQuery('.news').click(function(){
var target = jQuery(this).attr('data-target');
jQuery('.divelement').hide(); /*hide all divelement*/
jQuery(target).toggle(); /*Show the targeted divelement*/
console.log('Show' + target);
});
.divelement{
  display: none; /* By default divelement will be hidden */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="news" data-target="#myDIV1"> HELLO
</section> <!-- set targeted div id in data-target attribute -->

<section class="news" data-target="#myDIV2"> HI
</section>

<div class="divelement "id="myDIV1">
    This is my DIV1 element.
</div>

<div class="divelement "id="myDIV2">
    This is my DIV2 element.
</div>


推荐阅读