开发者

JQuery calling .click() on an autogenerated img inside

I'm using this

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("picHint").innerH开发者_运维百科TML=xmlhttp.responseText;
    }
  }

xmlhttp.open("GET","getpic.php?q="+str+"&t=" + Math.random(),true);
xmlhttp.send();

to pass in data and generate an undefined amount of pictures with the echo from PHP code in getpic.php

while($row = mysql_fetch_array($result)){
echo "<div id=" . $num . "><img src=QR/" . $row['img']".png></div>";
}

So these pictures do come out generated, however, now I'm trying to use

    $("#img").click(function () { 
        alert("Hi");
    });

but nothing gets alerted. The top function posts the stuff in the however i can't seem to call inside that id? How can I call the div or the img inside the outer div?


If you're generating content asynchronously, $.click() won't work unless you manually attach it to each new element. Try using $.live() instead:

// Applies itself to all <img /> tags.
$("img").live("click",function(){
  alert("Hi");
});

Be sure to check your ids as well, and note that using integers for your id is not a good practice. If you wish to use the numerical id of the image as the id, preface it with some type of alpha-value, such as #image19.


#symbol indicates filtering by ID in JQuery way. You need to filter by tag type which means you can use:

$("img").live(function () { 
    alert("Hi");
});

Also, try to follow HTML rules by covering your attribute values with quotes:

echo '<div id="'.$num.'"><img src="QR/'.$row['img'].'.png"></div>";


Try $('img').live('click',function(){.....

For one, #img would imply there's a dom node with the id="img" For two, any dom nodes added after the domready will not be able to be bound to a click() so you have to use live()


You should bind the click event after your ajax succeeds, OR use the live method. Like this:

   $("img").live("click", function () { 
        alert("Hi");
    });

Note that "#img" would select elements with id="img", but "img" will select all elements whose tag is <img ../>.

Hope this helps. Cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜