简体   繁体   中英

Linking images in Jquery from Flickr Feed

I am trying to link the images in my flikr feed. I keep running into issues being fairly new to Javascript. It took me awhile to get this far (even though flikr provides the basic code for the feed) The reason being I had made it allow you to enter multiple tags using the .split() function. I know this can be done with HTML strings.....but I know there must be a easier quicker way, even though I can't even figure them out that way...Feel free to improve my code if you please too, I am trying to keep it as short as possible.

$(function() {
        new WebApp(); 
        function WebApp() {



            this.form = $("<form><input id='tags' placeholder='tags'><input type='submit' value='submit'></form>").appendTo("header");


            this.form.submit(function (){ 
                $("#images").empty();
                var splitTest = $("#tags").val(); 
                //alert(splitTest);
                var arr = splitTest.split(",");
                //alert(arr.length);

                for(var i = 0; i <= arr.length; i++){
                    $.getJSON(
                        "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
                    {
                        tags: arr[i],
                        tagmode: "any",
                        format: "json"
                    },
                        function(data) {
                            $.each(data.items, function(i,item){
                                $("<img/>").attr("src", item.media.m).appendTo("#images");
                                if ( i == 20 ) return false;
                            });
                        }
                    );
                }

                return false; 
            }); 
        }

You can improve your code like this. Looks like you don't need WebApp anywhere else in the code then use anonymous function and execute it on page load.

$(function(){
    $("<form><input id='tags' placeholder='tags'><input type='submit' value='submit'></form>")
    .appendTo("header");
    .submit(function (){ 
        $("#images").empty();
        var arr = $("#tags").val().split(",");
        for(var i = 0; i <= arr.length; i++){
          $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
            {
               tags: arr[i],
               tagmode: "any",
               format: "json"
             },
             function(data) {
                 $.each(data.items, function(i,item){
                    $("<img/>").attr("src", item.media.m).appendTo("#images");
                    return  !( i == 20 );
                 });
            });
        }
        return false; 
    }); 
});

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