I have this script which works to show image alt tags.
$(document).ready(function() {
$('img').click(function(){
var altimg = $(this).attr('alt');
alert('Alt: '+ altimg);
});
});
I cant understand the method you would use to specify the element to search within for images (i only want to run this script on images within my content div).
How to implement getElementById in this instance is beyond me, can someone point me in the right direction?
I have this script which works to show image alt tags.
$(document).ready(function() {
$('img').click(function(){
var altimg = $(this).attr('alt');
alert('Alt: '+ altimg);
});
});
I cant understand the method you would use to specify the element to search within for images (i only want to run this script on images within my content div).
How to implement getElementById in this instance is beyond me, can someone point me in the right direction?
Share Improve this question edited Jan 22, 2014 at 11:49 Esko 4,2072 gold badges24 silver badges38 bronze badges asked Jan 22, 2014 at 11:45 user2010470user2010470 211 silver badge6 bronze badges 1- Apart from the 10 minute delay you have to wait for... – user2010470 Commented Jan 22, 2014 at 13:07
2 Answers
Reset to default 4Well. You can find all tag names within an ID by JavaScript with this method.
var x = document.getElementById("divID");
x = x.getElementsByTagName("TAG name to search for") // e.g. "img"
now x[0] will contain the first element with the tag IMG that occurs inside the div. OBS notice the .getElements ByTagName (elements are plural since you can get many, not just 1 like the ...ById method).
With jQuery you can find the images in a way somewhat like CSS
var x = $('#divID').find('img')
If you want to find images only with a specific class name (or something else) then modify the search to this.
var x = $('#divID').find('img').css('class', 'className')
These 2 ways will give you the elements stored as an array in the variable x.
From what I can understand, you only want this click event to be bound if the image is a child of a specific container (I'll call it #container
). Just prepend it to your selector:
$(document).ready(function() {
$('#container img').click(function(){
var altimg = $(this).attr('alt');
alert('Alt: '+ altimg);
});
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745235522a4617873.html
评论列表(0条)