javascript - 如何通过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>
解决方案
你可以通过这种方式使用 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>
推荐阅读
- python - 如何将文件与在 Python 中引用它们的 xml 关联?
- python - “命令”对象没有属性“has_permissions”
- asp.net-core - 机密客户端应用程序缓存 - GetAccountAsync
- c# - 为什么我不能在 Visual Studio 中移动 Windows 窗体?
- python - 从 python 在符号链接目录中运行 Makefile
- c# - 转到行/循环切换语句?
- rust - Rust - 类型的值不能从 `std::iter::Iterator<>` 构建
- c++ - c ++:原子变量的值在保存在局部变量中时无效
- .net - .net 核心网络应用程序 docker 映像如何在 Mac OS 上运行?
- css - 在导航栏中以小分辨率对齐搜索输入和提交按钮时遇到问题