Items.push variable using JavaScript

2019-09-17 21:22发布

问题:

I have an JSON array, that i manipulate inside my app,

...
$.each(data, function(key, val) {
    val = link + val;
    foto = val;
    foto = foto.substr(0, foto.lastIndexOf(".")) + ".jpg";
    /* Visualizza */
    var elem = document.getElementById("archivio-num");
    elem.innerHTML = '<a href="#"><img src="' + foto + '"></a>';
    elem.firstChild.onclick = function() {
        cordova.exec("ChildBrowserCommand.showWebPage", val);
    };
    items.push('<li id="' + key + '">' + elem.innerHTML + '</li>');
});
...

Now i'm trying to push all elements outside that are packed inside var elem. Puttin only + elem + give me an error [objectHTMLDivElement]. Is that possible?

回答1:

Exploiting jQuery further, you might want to try something like this :

...
var $ul = $("<ul/>");//jQuery object containing a dummy UL element in which to accumulate LI elements.
$.each(data, function(key, val) {
    var url = link + val;
    var foto = url.substr(0, url.lastIndexOf(".")) + ".jpg";
    var $a = $('<a/>').attr('href',url).append($("<img/>").attr('src',foto)).on('click', function() {
        cordova.exec("ChildBrowserCommand.showWebPage", $(this).attr('href'));
        return false;
    });
    $ul.append($('<li/>').attr('id',key).append($a));
});
$("#archivio-num").html($a);
...

Here, instead of accumulating the HTML in an array, actual LI elements are accumulated in a jQuery-wrapped UL element, which is available for further treatment (eg. insertion into the DOM) later in the code.



回答2:

<script type="text/javascript">
             $.getJSON('http://www..../json.php', function(data) {
                      var items = [];
                      var url;
                      var foto;
                      var link = 'http://www.bla.com/';
                      var $div = $("<div/>");

                      $.each(data, function(key, val) {
                             url = link + val;
                             foto = url.substr(0, url.lastIndexOf(".")) + ".jpg";
                             var $a = $('<a>').attr('href',url).append($("<img/>").attr('src',foto)).on('click',function(){
                                    cordova.exec("ChildBrowserCommand.showWebPage", $(this).attr('href'));
                                    return false;
                                    });
                                    $div.append($('<div/>').attr('id',key).append($a));
                             });
                             $("#archivio-num").html($a);                           
                      });
            </script>