【问题标题】:Jquery show and hide shows one div but not anotherJquery show and hide 显示一个 div 但不显示另一个
【发布时间】:2019-03-22 10:54:15
【问题描述】:

我正在尝试使用一个 href 来显示和隐藏另外两个 div。默认情况下会显示一个 div,但第二个 div 仍然隐藏。

    <a href="#ben1" class="fa fa fa-times closer" > 
    <p> link text </p>
   </a>
    <a href="#ben2" class="fa fa fa-times closer" > 
    <p> link text </p>
   </a>


<div class="resume right-col" id="ben1">
<p>Hello this is a test </p>
</div> 

<div class="resume right-col" id="ben2">
<p>Hello this is a test </p>
</div> 


<div class="resume right-col" id="ben1">
<p>second text area i need displayed by default</p>
</div> 

<div class="resume right-col" id="ben2">
<p>second text area i need hidden initially/p>
</div> 


<script>
$('.resume') .hide()
$('#ben1').show();
$('a[href^="#"]').on('click', function(event) {
$('.resume') .hide()
var target = $(this).attr('href');

$('.resume'+target).toggle();
e.preventDefault();
});
</script>

当页面加载时,ID 为“ben1”的第二个 div 始终处于隐藏状态。我需要在脚本中添加一些内容吗?

【问题讨论】:

  • 重复的id 无效。
  • ID 必须是唯一的

标签: jquery html css


【解决方案1】:

作为示例,您可以创建一个显示而不是使用 ID 的类..

    <a href="#ben1" class="fa fa fa-times closer" > 
    <p> link text </p>
   </a>
    <a href="#ben2" class="fa fa fa-times closer" > 
    <p> link text </p>
   </a>


<div class="resume right-col class1" id="ben1">
<p>Hello this is a test </p>
</div> 

<div class="resume right-col class2" id="ben2">
<p>Hello this is a test </p>
</div> 


<div class="resume right-col class1" id="ben1">
<p>second text area i need displayed by default</p>
</div> 

<div class="resume right-col class2" id="ben2">
<p>second text area i need hidden initially/p>
</div> 


<script>
$('.resume') .hide()
$('.class1').show();
$('a[href^="#"]').on('click', function(event) {
$('.resume') .hide()
var target = $(this).attr('href');

$('.resume'+target).toggle();
e.preventDefault();
});
</script>

【讨论】:

    【解决方案2】:

    一个 id 在一个页面中应该是唯一的,所以你会混淆 jquery。

    https://css-tricks.com/almanac/selectors/i/id/

    尝试改用类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 2015-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-30
      • 1970-01-01
      相关资源
      最近更新 更多