[英]How do I get the img src inside a <li><div> tag?
I'm trying to get the src of an image from a selected list item. 我正在尝试从选定的列表项中获取图像的src。 The HTML looks like this:
HTML看起来像这样:
<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: 我现在可以从所选列表元素中获取玩家ID,如下所示:
jQuery 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? 如何从选定的列表元素中获取img src?
If user_id
corresponds to number in player ID, then try: 如果
user_id
对应于玩家ID中的数字,请尝试:
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. 使用jQuery获取图像元素,然后读取其src属性。
$('#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").find("li")
当"$("#myDiv li")
做得很好时, $("#myDiv").find("li")
然后,在这一点上,以下就足够了:
$('#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. 就个人而言,我倾向于在ID上使用split来获取user_id,(。
.attr('id').split('_')[1]
),但看到你必须修改你的代码如果你需要改变你的前缀或命名约定,我认为这并不重要。 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. 它可能会影响性能(因为拆分似乎总是更快,虽然我不记得为什么),如果你有很多这些要一次解析,但除此之外,对于一对一的操作,substr应该工作正好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.