0

Basically, on clicking any image on a html page I want the id associated to be passed to a function. This is what I have tried. It seems I am making a minor mistake here as I am getting the first id passed no matter what image I click from the array. I tried $(this).attr("id") as well, but did not work.

            for(var i=0;i<jsonObj.length-1;i++){
                var rows = '';
                var bg_img = jsonObj[i].img;
                var bg_img = decodeURIComponent(bg_img);                    
                rows = "<img id='" + jsonObj[i].source_id + "' src='" + bg_img + "'/>";                 
                document.getElementsByClassName('subscription')[i].innerHTML = rows;
            }                           

            $("body").delegate(".subscription", "click", function() {
                //  var id = $(this).attr("id");
                    alert("Welcome Test " + $('img').attr("id"));
                return false;
            });

2 Answers 2

1
$("img").click(function()
{
    var id = $(this).attr("id");
});
Sign up to request clarification or add additional context in comments.

Comments

0

Your $('img') selector is not confined to any specific area, so it will give you the first image on the entire page.

Try $('img',this) instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.