I'm trying to get the src of an image from a selected list item. The HTML looks like this:
<li id="player_7">
<div class="nailthumb-container square-thumb">
<img src="../photos/files/7/thumb/6c0f1676cdcb1a9a5215db3e12572450.jpeg" />
</div>
</li>
I can currently get the player ID from the selected list element like so:
jQuery
$('#myDiv').find("li").click(function() {
var user_id = $(this).attr('id').substr(7);
});
How can I get the img src from a selected list element?
If user_id
corresponds to number in player ID, then try:
var src = $("#player_" + user_id + " img").prop("src");
Otherwise, respectively to the clicked list item:
$("#myDiv").find("li").click(function() {
var src = $("img", this).prop("src");
});
Get image element using jQuery then read its src property.
$('#myDiv').find("li").click(function() {
var user_id = $(this).attr('id').substr(7);
var src = $("img", this)[0].src;
});
May I ask why you're doing $("#myDiv").find("li")
when "$("#myDiv li")
should do just fine? Then, at that point, the following would suffice:
$('#myDiv li").click(function() {
var user_id = $(this).attr('id').substr(7);
var src = $("img",this).attr('src');
// ...
});
Personally, I'd favor using a split on the ID to get the user_id, ( .attr('id').split('_')[1]
), but seeing as you'd have to modify your code either way if you needed to change your prefix or naming convention, I don't suppose that really matters much. It might affect performance (as split has always seemed to be faster, though I can't remember why), if you had a lot of these to parse at one time, but otherwise, for one-by-one operations, substr should work just fine.
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.