Say I have the following JavaScript codes

function img_find() {
    var imgs = document.getElementsByTagName("img");
    var imgSrcs = [];

    for (var i = 0; i < imgs.length; i++) {
        imgSrcs.push(imgs[i].src);
    }

    return imgSrcs;
}

and

function link_find() {
    var links = document.getElementsByTagName("a");
    var linkHrefs = [];

    for (var i = 0; i < links.length; i++) {
        linkHrefs .push(links[i].href);
    }

    return linkHrefs;
}

I am going to actually use addEventListerner to create a custom context menu when a link or image is hold on. My plan is to combine both functions into one but then how do I identify if the http returned is for the link or image? Since not all image source scr end with an identifiable image extension.

有帮助吗?

解决方案

You could return an extra parameter, using an object:

return {links: links, type: "img"};

You can then use something like this:

var links = find();

if(links["type"] === "img")
    console.log("I'm an image!");
else if(links["type"] === "href")
    console.log("I'm a link!");
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top