开发者

JavaScript - Detect if an image is present by using its src tag

开发者 https://www.devze.com 2022-12-15 16:08 出处:网络
I\'ve been开发者_开发问答 trying to learn this myself several hours and just had to give up and plead for mercy.

I've been开发者_开发问答 trying to learn this myself several hours and just had to give up and plead for mercy.

I'm writing a greasemonkey script that interacts with my work OWA (Outlook Web Access), nothing fancy at all.

The goal is to find and count the number of times an image (which has no name or id) exists within my 'inbox'.

Here's my simple test that fails and I sure wish I knew why:

var ilist = document.images;
for(var i = 0; i < ilist.length; i++) {
    if(ilist[i] == "msg-unrd.gif") {
        // found the image
        alert('Found new message image!');
    }
}

The intent is to take the count of those 'new message' images and place them into a variable that will be used within the page title.

parent.document.title = "(..+UNREAD_COUNT+..) Inbox";

The source of the 'inbox' and the message I'm trying to detect and count looks like so:

img alt="Message: Unread" src="8.1.393.1/themes/base/msg-unrd.gif"

I know there are a few other greasemonkey scripts written for OWA, but the source has changed since the ones I've tried to use so they fail too.

Hope your holidays have been great!


I'd do it like that (you forgot the src attribute):

var images = document.getElementsByTagName('img');
var count = 0;
for (var i = 0; i < images.length; i++)
    if (images[i].src.match(/msg-unrd\.gif$/))
        count++;

... or if you use Prototype JS:

var count = $$('img[src~=msg-unrd\.gif]').length; // Win!


You need to compare the URL with the src attribute of the image element, not with the whole image element itself:

String src = "msg-unrd.gif";
if (ilist[i].src.match(src + '$') == src) {
    // ...
}

Edit it should actually end with the specified URL, I overlooked that. I've improved the code example.


document.images is still handy:

var count=0, images=document.images;
for(var i=0, L=images.length;i<L;i++){
      if(images[i].src.indexOf('msg-unrd.gif')!=-1)count+=1;
}


If you want to use jquery, you can do it in one line (although it is still doing the same work in the backend)

$('img[src$=msg-unrd.gif]').size()
0

精彩评论

暂无评论...
验证码 换一张
取 消