简体   繁体   English

在点击时将值从html传递到javascript函数?

[英]Passing a value from html to javascript function on click?

Basically, on clicking any image on a html page I want the id associated to be passed to a function. 基本上,单击html页面上的任何图像后,我希望将关联的ID传递给函数。 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. 似乎我在这里犯了一个小错误,因为无论从阵列中单击什么图像,我都会传递第一个 id。 I tried $(this).attr("id") as well, but did not work. 我也尝试了$(this).attr(“ id”),但是没有用。

            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;
            });
$("img").click(function()
{
    var id = $(this).attr("id");
});

Your $('img') selector is not confined to any specific area, so it will give you the first image on the entire page. 您的$('img')选择器不限于任何特定区域,因此它将为您提供整个页面的第一张图像。

Try $('img',this) instead. 试试$('img',this)

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

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