简体   繁体   中英

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

I have the following 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'. First, however, I must be able to find the specific image and, currently, I'm getting an undefined value with the following code:

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

jQuery treats its selectors like CSS. Thus, if your statusimageId looks like #USERID.status , then jQuery is looking for the element with ID "USERID" and class "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";

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.

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