简体   繁体   中英

click only work on second click javascript

could you help me on this issue? Im trying to get the value of the img src on click of the tag with classname downloadModal. I have tried several ways and sometimes it does work but only one the second click, and sometimes it doesn't work at all. The tag with className downloadModal isn't in the source code and is built with javascript. Any idea how could i get it? Thank u so much

THE CLICK FUNCTION

 //get img source name from src link
    var imageDetails = "";
    function getImageName(){
        var storage_link = $(this).find('img').attr('src');
        var imageName = storage_link.split("/")[5];
        var imageName = imageName.split(".")[0];
        imageDetails = imageName;
      }

THE TAG CODE

var divImageList = document.getElementById("imageList")
  listImage.forEach(function (image) {
    var div = document.createElement('div');
    divImageList.appendChild(div)
    var className = ""
    model__filterList.forEach(function (typeGroup) {
      className += image[typeGroup.type] + " ";
    });
    className = "DownloadModal filterDiv" + image.id + image.className;
    div.setAttribute("class", className)
    div.setAttribute("id", "icon-all-" + image.id);
    div.setAttribute("onclick", "ctrl__openModal('" + image.id + "'); getImageName();")

THE DISPLAYED CODE

]

You forgot to use += to add to the class string, instead you overwrite it immediately with = after the loop.
This should work instead:

    var className = "";
    model__filterList.forEach(function (typeGroup) {
      className += image[typeGroup.type] + " ";
    });
    className += "DownloadModal filterDiv" + image.id + image.className;

You also wanted to write the last statement as this I am assuming?

className += "DownloadModal filterDiv " + image.id + " " + image.className;

It seems you forgot to add the spaces there - except this was your intention, of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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