简体   繁体   English

如何使用字符串值正确查找(并最终更改)img src属性?

[英]How to correctly find (and ultimately change) img src attribute using string value?

I have the following HTML: 我有以下HTML:

<img id="unique.name.status" class="icon" src="OffStatus.png" alt="OFFLINE" />

At some point a client refreshes and I may need to change the image src and alt with id 'unique.name.status'. 有时客户端会刷新,我可能需要更改ID为'unique.name.status'的图像srcalt First, however, I must be able to find the specific image and, currently, I'm getting an undefined value with the following code: 但是,首先,我必须能够找到特定的图像,并且目前,我使用以下代码获得undefined值:

statusimageId = "#" + user_id + ".status";
alert(statusimageId); // confirmed valid: '#unique.name.status'

statusimageSource = $(statusimageId).attr("src");   // returns 'undefined'
alert(statusimageSource);

NOTE: user_id is a value returned from JSON 注意: user_id是从JSON返回的值

jQuery treats its selectors like CSS. jQuery将其选择器视为CSS。 Thus, if your statusimageId looks like #USERID.status , then jQuery is looking for the element with ID "USERID" and class "status". 因此,如果您的statusimageId看起来像#USERID.status ,则jQuery正在查找ID为“ USERID”且类为“ status”的元素。 You'll want to use a different convention than . 您可能要使用与以外的约定. to add your "status" flag. 添加您的“状态”标志。 Try: 尝试:

<img id="unique_name_status" class="icon" src="OffStatus.png" alt="OFFLINE" />

and

statusimageId = "#" + user_id + "_status";

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

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