使用 jQuery 显示目录中的图像?

Display image from directory using jQuery?

我目前正在学习网络开发的基础知识,但我还没有遇到解决方案的一件事是使用 jQuery 从目录中获取图像。 如果我有一个复选框定义如下...

<input id="check" type="checkbox">

...我如何从目录中获取图像,并根据复选框的当前状态将其显示在 <div> 中(不弄乱 HTML)?到目前为止我发现的是这个,但这只是为了显示 <div> 的现有内容,对吗?

$(document).ready(function(){
    $('#check').click(function(){
        if(!$(this).is(':checked')){
            ("div").show();
        }
    });
});             

我不想接触HTML的原因是我想更深入地了解jQuery更强大的功能(我不想养成坏习惯),但这被证明是我自己做的一件困难的事情。我真的很感激任何帮助(或只是一些提示)!

tl;dr:选中框 = 图片,未选中 = 无图片。 jQuery只是因为一些原因。

如果您 HTML 看起来像这样:

<input id="check" type="checkbox">
<div class="image-to-show-and-hide"><img id="image-to-place" /></div>

你可以让你的 jQuery 看起来像这样:

$(document).ready(function(){
  $('#check').click(function(){
    // Avoiding the negation where possible can make code a easier to read.
    if($(this).is(':checked')){
      // Show the div with the specified class:
      $(".image-to-show-and-hide").show();
      // And show the image by filling its "src" attribute.
      $("#image-to-place").attr("src","http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg");
    }
    else {
      // Otherwise, hide the div.
      $(".image-to-show-and-hide").hide();
    }
  });
});

https://jsfiddle.net/9gdpdLmb/1/

你可以(假设 div 存在)

$(document).ready(function () {
    //create a reference to the div which can be reused later
    var $div = $('div'),
        $img;
    $('#check').change(function () {
        //set the display status of the div based on checked state of the checkbox
        $div.toggle(this.checked);
        if (this.checked) {
            //if it is checked and the img is not present create one
            if (!$img) {
                $img = $('<img />', {
                    src: '//placehold.it/64/00ff00'
                }).appendTo($div);
            }
        }
    });
});

演示:Fiddle