admin管理员组

文章数量:1415491

Everyone:

I'm trying to grab the source URLs of images from one page and use them in some JavaScript in another page. I know how to pull in images using JQuery .load(). However, rather than load all the images and display them on the page, I want to just grab the source URLs so I can use them in a JS array.

Page 1 is just a page with images:

<html>
  <head>
  </head>
  <body>
    <img id="image0" src="image0.jpg" />
    <img id="image1" src="image1.jpg" />
    <img id="image2" src="image2.jpg" />
    <img id="image3" src="image3.jpg" />
  </body>
</html>

Page 2 contains my JS. (Please note that the end goal is to load images into an array, randomize them, and using cookies, show a new image on page load every 10 seconds. All this is working. However, rather than hard code the image paths into my javascript as shown below, I'd prefer to take the paths from Page 1 based on their IDs. This way, the images won't always need to be titled "image1.jpg," etc.)

<script type = "text/javascript">
        var days = 730;
        var rotator = new Object();
        var currentTime = new Date();
        var currentMilli = currentTime.getTime();
        var images = [], index = 0;
        images[0] = "image0.jpg";
        images[1] = "image1.jpg";
        images[2] = "image2.jpg";
        images[3] = "image3.jpg";
        rotator.getCookie = function(Name) { 
            var re = new RegExp(Name+"=[^;]+", "i"); 
            if (document.cookie.match(re)) 
                return document.cookie.match(re)[0].split("=")[1];
                return''; 
        }
        rotator.setCookie = function(name, value, days) { 
            var expireDate = new Date();
            var expstring = expireDate.setDate(expireDate.getDate()+parseInt(days));
            document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/";
        }
        rotator.randomize = function() {
            index = Math.floor(Math.random() * images.length);
            randomImageSrc = images[index];
        }
        rotator.check = function() {
            if (rotator.getCookie("randomImage") == "") {
                rotator.randomize();
                document.write("<img src=" + randomImageSrc + ">");
                rotator.setCookie("randomImage", randomImageSrc, days);
                rotator.setCookie("timeClock", currentMilli, days);
            }
            else {
                var writtenTime = parseInt(rotator.getCookie("timeClock"),10);
                if ( currentMilli > writtenTime + 10000 ) {
                    rotator.randomize();
                    var writtenImage = rotator.getCookie("randomImage")
                    while ( randomImageSrc == writtenImage ) {
                        rotator.randomize();
                    }
                    document.write("<img src=" + randomImageSrc + ">");
                    rotator.setCookie("randomImage", randomImageSrc, days);
                    rotator.setCookie("timeClock", currentMilli, days);
                }
                else {
                    var writtenImage = rotator.getCookie("randomImage") 
                    document.write("<img src=" + writtenImage + ">");
                }
            }
        }
        rotator.check()
    </script>

Can anyone point me in the right direction? My hunch is to use JQuery .get(), but I've been unsuccessful so far.

Please let me know if I can clarify!

Everyone:

I'm trying to grab the source URLs of images from one page and use them in some JavaScript in another page. I know how to pull in images using JQuery .load(). However, rather than load all the images and display them on the page, I want to just grab the source URLs so I can use them in a JS array.

Page 1 is just a page with images:

<html>
  <head>
  </head>
  <body>
    <img id="image0" src="image0.jpg" />
    <img id="image1" src="image1.jpg" />
    <img id="image2" src="image2.jpg" />
    <img id="image3" src="image3.jpg" />
  </body>
</html>

Page 2 contains my JS. (Please note that the end goal is to load images into an array, randomize them, and using cookies, show a new image on page load every 10 seconds. All this is working. However, rather than hard code the image paths into my javascript as shown below, I'd prefer to take the paths from Page 1 based on their IDs. This way, the images won't always need to be titled "image1.jpg," etc.)

<script type = "text/javascript">
        var days = 730;
        var rotator = new Object();
        var currentTime = new Date();
        var currentMilli = currentTime.getTime();
        var images = [], index = 0;
        images[0] = "image0.jpg";
        images[1] = "image1.jpg";
        images[2] = "image2.jpg";
        images[3] = "image3.jpg";
        rotator.getCookie = function(Name) { 
            var re = new RegExp(Name+"=[^;]+", "i"); 
            if (document.cookie.match(re)) 
                return document.cookie.match(re)[0].split("=")[1];
                return''; 
        }
        rotator.setCookie = function(name, value, days) { 
            var expireDate = new Date();
            var expstring = expireDate.setDate(expireDate.getDate()+parseInt(days));
            document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/";
        }
        rotator.randomize = function() {
            index = Math.floor(Math.random() * images.length);
            randomImageSrc = images[index];
        }
        rotator.check = function() {
            if (rotator.getCookie("randomImage") == "") {
                rotator.randomize();
                document.write("<img src=" + randomImageSrc + ">");
                rotator.setCookie("randomImage", randomImageSrc, days);
                rotator.setCookie("timeClock", currentMilli, days);
            }
            else {
                var writtenTime = parseInt(rotator.getCookie("timeClock"),10);
                if ( currentMilli > writtenTime + 10000 ) {
                    rotator.randomize();
                    var writtenImage = rotator.getCookie("randomImage")
                    while ( randomImageSrc == writtenImage ) {
                        rotator.randomize();
                    }
                    document.write("<img src=" + randomImageSrc + ">");
                    rotator.setCookie("randomImage", randomImageSrc, days);
                    rotator.setCookie("timeClock", currentMilli, days);
                }
                else {
                    var writtenImage = rotator.getCookie("randomImage") 
                    document.write("<img src=" + writtenImage + ">");
                }
            }
        }
        rotator.check()
    </script>

Can anyone point me in the right direction? My hunch is to use JQuery .get(), but I've been unsuccessful so far.

Please let me know if I can clarify!

Share Improve this question asked Oct 8, 2012 at 20:57 SDDSDD 231 silver badge3 bronze badges 5
  • 1 You can't use get() function with plain html as target. – Radi Commented Oct 8, 2012 at 21:02
  • Thanks for your help. I haven't tried too much with .get — just to see if I could single out img src from another page: $.get('page1.html', function(data) { var imageonly = $(data).attr("src"); $('.result').html(imageonly); }); But this is really quite far from what I want, which is to load it into the JS above. Sorry, I'm quite new to JS/JQ. – SDD Commented Oct 8, 2012 at 21:06
  • Is there a reason you use cookies? Why not use setInterval? – saml Commented Oct 8, 2012 at 21:30
  • I'm not familiar with setInterval. I need this to work across several pages. For example, I want visitors to see one image for x amount of time, even if they change pages. Then, once that amount of time has passed, a different image will load upon visiting a new page. Would setInterval work for that? – SDD Commented Oct 8, 2012 at 21:39
  • you cant do this cross-page consistency with javascript alone (unless you ajax in the page content itself and never actually "leave" the page) – Mike H. Commented Oct 8, 2012 at 21:42
Add a ment  | 

3 Answers 3

Reset to default 2

Try this.

<script>
$.get('http://path/to/page/1', function(data) {
    var imgs = $('<div/>').html(data).find('img');
    imgs.each(function(i, img) {
        alert(img.src); // show a dialog containing the url of image
    });
});
</script>

I don't understand why you want to use cookies for this. You should get page1, find the images, and then use setInterval to update the src.

$.get('page1.html', function(data, status) { // get the page with the images
    var parser = new DOMParser();
    var xmldoc = parser.parseFromString(data, "text/html");  //turn it into a dom

    var imgs = xmldoc.getElementsByTagName('img'); //get the img tags
    var imageSrcs = Array.prototype.slice.call(imgs).map(function(img) {
       return img.src; //convert them to an array of sources
    });

    setInterval(function() { // run this every 10 seconds
        var imags = document.getElementsByTagName('img'); // find the images on this page
        Array.prototype.slice.call(imgs).forEach(function(img) {
             var imgSrc = Math.floor(Math.random()*imageSrcs.length);  //get a random image source
             img.src = imageSrcs[imgSrc];  //set this image to the src we just picked at random
        });
    }, 10000);

}, 'html');

why not use ajax? you could .load() the section of your external page that contains all of the images into a hidden container and then extrapolate the information you need through a callback.

external.html

<html>
....
    <div id="imgContainer">
         <img id="image0" src="image0.jpg" />
         <img id="image1" src="image1.jpg" />
         <img id="image2" src="image2.jpg" />
         <img id="image3" src="image3.jpg" />
    </div>
</html>

ajax.js

function ajaxContent(reg, extReg) {

var toLoad = 'external.html' + extReg;

function loadContent() {
    $(reg).load(toLoad,'',getSrcPaths())
}

function getSrcPaths() {
    $(reg + ' #image0').delay(200).fadeIn('slow');
    $(reg + ' #image1').delay(200).fadeIn('slow');
    // or however you want to store/display the images
}
}

Then onload just make a call to ajaxContent something like

<body onload="ajaxContent('#hiddenContainer','#imgContainer')">
     ....
</body>

This of course is not really relevant if your images are large or if page load is negatively affected. Although since you actually have the images now, you might even just display them rather than hide them. Depends on exactly how much you need to manipulate the originals I suppose.

本文标签: javascriptGet Image Source URLs from a Different Page Using JSStack Overflow