如果未选中该复选框,请隐藏标记和 img

Hide a tag and img if the checkbox is not checked

本文关键字:隐藏 img 复选框 如果      更新时间:2023-09-26

>我在叠加层中有一些复选框,只要不选中它们,就<img>并且不应该看到<a>标签。

<a><img>标记的 HTML:

<div id="extra">    
    <a href="detail.html?event=theater&datum=01_01" class = "theater">
        <img src="img/theater.png" alt="Theater">
    </a>
    <img src="img/literatur.png" alt="Literatur">
</div>

这是复选框:

<div class="tags">
    <label>
        <input  type="checkbox" rel="alles" id="checkme"/>
        Alles
    </label>
</div>

这是函数:

$("#extra").css("display","none");
$("#checkme").click(function(){
    if ($("#checkme").is(":checked"))
    {
        $("#extra").show("fast");
    } else{
         $("#extra").hide("fast");
    }
});

我也尝试了其他一些方法,但没有任何帮助。

在我看来这更优雅

$("#extra").hide();
$("#checkme").on("click",function(){
  $("#extra").toggle(this.checked);
});

我假设您在相关对象渲染后执行上述操作,否则您需要

$(function() {
  $("#extra").hide();
  $("#checkme").on("click",function(){
    $("#extra").toggle(this.checked);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="extra">    
    <a href="detail.html?event=theater&datum=01_01" class = "theater">
        <img src="http://png-1.findicons.com/files/icons/2711/free_icons_for_windows8_metro/128/theatre_masks.png" alt="Theater">
    </a>
    <img src="http://icons.iconarchive.com/icons/itzikgur/my-seven/128/Books-2-icon.png" alt="Literatur">
</div>
<div class="tags">
    <label>
        <input  type="checkbox" rel="alles" id="checkme"/>
        Alles
    </label>
</div>

这个小提琴 http://jsfiddle.net/yfnen44e/有一个工作的例子。我假设您只想在 #extra 中隐藏链接的图像,而不是整个div。

var $extra = $('#extra a').hide();
$('#checkme').on('click', function (){
   $extra.toggle(this.checked);
});

尝试以下更改:将代码放入$(document).ready(function () {your code here});

$(document).ready(function () {
    $("#extra").css("display", "none");
    $("#checkme").click(function () {
        if ($("#checkme").is(":checked")) {
            $("#extra").show("fast");
        } else {
            $("#extra").hide("fast");
        }
    });
});

现场演示

有很多

方法可以做到这一点,其中之一是使用 jQuery .prop 方法来获取属性的值。

  $("#checkme").click(function() {
    if ($("#checkme").prop('checked')) {
      $("#extra").show("fast");
    } else {
      $("#extra").hide("fast");
    }
  });
#extra {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="extra">
  <a href="detail.html?event=theater&datum=01_01" class="theater">
    <img src="img/theater.png" alt="Theater" />
  </a>
  <img src="img/literatur.png" alt="Literatur" />
</div>
<div class="tags">
  <label>
    <input type="checkbox" rel="alles" id="checkme" />Alles</label>
</div>

注意:使用 jQuery . CSS 将内联 CSS 添加到文档中。