要使用javascript在单击p元素时获取不同div元素的id吗
我有一个带有p标签和div元素的页面,div元素在开始时设置为display:none,因此,我只想在单击p标签时在body标签内显示不同的div,如下所示,但我在获取div的不同id时遇到了困难。请帮我摆脱这种情况。下面是我的代码。谢谢要使用javascript在单击p元素时获取不同div元素的id吗,javascript,Javascript,我有一个带有p标签和div元素的页面,div元素在开始时设置为display:none,因此,我只想在单击p标签时在body标签内显示不同的div,如下所示,但我在获取div的不同id时遇到了困难。请帮我摆脱这种情况。下面是我的代码。谢谢 <script> function toggle(id)// here is the function which gets the different ids of the div { var element = do
<script>
function toggle(id)// here is the function which gets the different ids of the div
{ var element = document.getElementById(id);
for(i=1; i<3; i++)
{
if(element[i].style.display == "none")
{
element[i].style.display = "block";
}
else
{
element[i].style.display = "none"
}
}
}
</script>
<body>
<p onclick="toggle('div1')">Sentence1</p>
<p onclick="toggle('div2')">Sentence2</p>
<div id="div1" name="Name 1" style="display:none; width:400px; height:300px; border:1px solid black; background-color:yellow;" id="div1">Barun Ghatak</div>
<div id="div2" style="display:none; width:400px; height:300px; border:1px solid black; background-color:black;" id="div2">Bhoopi</div>
</body>
每个div只有一个,因此不需要循环。只用
function toggle(id)// here is the function which gets the different ids of the div
{
var element = document.getElementById(id);
if(element.style.display == "none")
{
element.style.display = "block";
}
else
{
element.style.display = "none"
}
}
document.getElementById返回单个对象,而不是数组
如果您想同时获取这两个div,我建议使用一个类来获取它们。如果您希望一次只显示一个div,例如,如果您正在构建一个选项卡,则可以使用此代码先隐藏所有其他div,然后只显示要切换的div。否则,如果您愿意切换它们,您可以使用其他人发布的代码 JS小提琴演示: HTML JS
为什么要指定id 2两次。。?循环的目的是什么?请不要使用内联样式…谢谢先生,我很感激你的宝贵意见,我会试试这个。
<p onclick="toggle('div1');">Sentence1</p>
<p onclick="toggle('div2');">Sentence2</p>
<div id="content">
<div id="div1" name="Name 1" style="display:none; width:400px; height:300px; border:1px solid black; background-color:yellow;" id="div1">Barun Ghatak</div>
<div id="div2" style="display:none; width:400px; height:300px; border:1px solid black; background-color:black;" id="div2">Bhoopi</div>
</div>
function toggle(id)
{
//Hide all other divs first
var divs = document.getElementById('content').childNodes;
for ( var i = 0; i < divs.length; i++ ) {
if ( divs[i].nodeName == "DIV" ) {
var div = document.getElementById(divs[i].id);
div.style.display = "none";
}
}
//Show the one that's being requested
var element = document.getElementById(id);
element.style.display = "block";
}