Items.push variable using JavaScript

老子叫甜甜 提交于 2019-12-11 20:39:44

问题


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>


来源:https://stackoverflow.com/questions/11627541/items-push-variable-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!