简体   繁体   English

自动生成的图像不可点击

[英]Auto-Generated images are not clickable

I have 4 images on my webpage, when I click one of them, the clicked image is highlighted. 我的网页上有4张图像,当我单击其中之一时,所单击的图像将突出显示。 I achieve using this : 我实现了使用此:

JS1 : JS1:

var ImageSelector = function() {
  var imgs = null;
  var selImg = null;

  return {
     addImages: function(container) {
        imgs = container.getElementsByTagName("img");
        for(var i = 0, len = imgs.length; i < len; i++) {
           var img = imgs[i];
           img.className = "normal";
           img.onclick = function()  {
              if(selImg)   {
                 selImg.className = "normal";
              }
              this.className = "highlighted";
              selImg = this;
              urlSet(this.src);
           };
        }
     }
  };
}();

JS 2: JS 2:

var div = document.getElementById("menu");
ImageSelector.addImages(div);

CSS : CSS:

   .normal {
      border:none;
   }
   .highlighted {
     border:8px solid #19A3FF;
   }

I have inserted a jQuery code that displays all images in a folder, which is this : 我插入了一个jQuery代码,用于显示文件夹中的所有图像,这是这样的:

var dir = "images/";
var fileextension = ".jpg";
$.ajax({
    //This will retrieve the contents of the folder if the folder is configured as 'browsable'
    url: dir,
    success: function (data) {
        //Lsit all png file names in the page
        $(data).find("a:contains(" + fileextension + ")").each(function () {
            var filename = this.href.replace(window.location, "").replace("http://example.com/", "");
            $(".menu").append($("<img src=" + dir + filename + " width=300 height=300>"));
        });
    }
});

HTML code is this : HTML代码是这样的:

    <div>
        <div id="menu" class = "menu">
</div></div>

When I inserted that jQuery code, the images are displayed but not clickable anymore. 当我插入该jQuery代码时,将显示图像,但不再可单击。 How can I make them clickable again? 如何使它们再次可点击? Thanks. 谢谢。

Mohit Arora - call your function ImageSelector in success event after append image or use delegation. Mohit Arora-在追加图像或使用委托后成功事件中调用函数ImageSelector。

I'll explain why, It's because you set the .onclick function before the images are loaded. 我将解释原因,这是因为在加载图像之前设置了.onclick函数。 An ajax call is executed after your code because ajax is async. 因为ajax是异步的,所以在您的代码之后执行了ajax调用。 If you want to hook anything to something you called via ajax always do it in the succes event. 如果您想将任何东西链接到通过ajax调用的内容,请始终在succes事件中执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM