如何从$ .getJSON更改img src?

时间:2017-06-06 17:32:24

标签: image getjson src

我想使用JS和JSON更改let layer = CAShapeLayer() let path = UIBezierPath(rect: self.view.bounds) let frameview = UIView(frame: CGRect(x:60,y:120,width:200,height:200)) frameview.layer.borderColor = UIColor.red.cgColor frameview.layer.borderWidth = 2 let tpath = UIBezierPath(rect: frameview.frame) path.append(tpath) layer.path = path.cgPath layer.fillRule = kCAFillRuleEvenOdd path.usesEvenOddFillRule = true let blurview = UIView(frame: self.view.bounds) let blur = UIVisualEffectView (effect: UIBlurEffect (style: UIBlurEffectStyle.dark)) blur.frame = blurview.bounds let maskView = UIView(frame: self.view.frame) maskView.backgroundColor = UIColor.black maskView.layer.mask = layer //blurview.layer.mask = layer blur.mask = maskView let imview = UIImageView(frame: self.view.bounds) imview.image = UIImage(named: "embed2") view.addSubview(imview) blurview.addSubview(blur) view.addSubview(blurview) view.addSubview(frameview) (在HTML代码上)的内容,但我无法获得。

有两个img src来电是因为我不知道进入同一个电话,得到一个数组和一个对象,对不起这个坏代码但是我想记住你这不是问题(这段代码很粗糙,但它有效)

问题:

点击$.getJSON图标调用fa fa-search-plus fa-3x时,在对话框页面(使用JQM 1.4.5 sintax)上替换(将要)$('.imagen-go').click(function(),这样就会显示图像来自JSON。

我认为:由于imagen-to-show是异步的,所以在获取$.getJSON之前,JS运行其余代码(比files = files['files'];更快)到达变量$.getJSON时还是空的。请阅读我对内联代码的注释,以便更好地理解。

我该如何解决?

JS代码:

subLoc8

HTML:专注于问题(对话框页面):

$( document ).on( "pageinit", "#page-1", function( event ) {

var parser_origin = 'http://xxxxxx.com';
var path_thumb1 = '/upload_menus/thumb1/' + id_establecimiento() +'/';
var img_tmpl = '/upload_tmpl/upload.jpg';


   //get data[] (array). 1er JSON. start
    $.getJSON( parser_origin + "/_country/spain/v137/lacarte.restaurants.back/alacarte/php/r.shw.menu.php", { site: id_establecimiento(),idioma: to_translate(),traduccion: traduc_usada() }, function(data){

          for (var i=0, len=data.length; i < len; i++) {
              console.log(data[i]);
          }
              data = data['data']; 

    //get files{} (object) . 2nd JSON. start
    $.getJSON( parser_origin + "/_country/spain/v137/lacarte.restaurants.back/alacarte/php/r.shw.menu.php", { site: id_establecimiento(),idioma: to_translate(),traduccion: traduc_usada() }, function(files){ //files // ori

            for (var z=0, len=files.length; z < len; z++) {
              console.log(files[z]); //required!!
                }
            files = files['files']; 

// Now two nested $.each(), to iterate on 1st JSON and get objects of 2nd JSON. It`s work fine!

// 1st loop. sections 
$.each(data, function (i, v) {
collapsible.push(v.es_un); 

$.each(collapsible, function (i, v) {
    if ($.inArray(v, seccion) === -1) {
        seccion.push(v);
    }
    });
});

// 2nd loop. items into sections 
$.each(seccion, function (i, loc) {
var parent = loc;
var elements = '';

$.each(data, function (x, sub) {
    var subLoc = sub.nombre;
    var subLoc2 = sub.condimentos;
    var subLoc5 = sub.DT_RowId; 
    var subLoc6 = sub.alergeno; 
    var subLoc7 = sub.nota_item; 
    var subLoc8 = sub.image; 
    // check if have a picture  
      if  (subLoc8 == null || subLoc8 == '')   {
          var foto_mostrar_listview = img_tmpl;  // if not, assign a dummy image for not empty  
        }
      else if  (subLoc8 != null){// if, yes, get it 
          var foto_mostrar_listview = files.files_menus[subLoc8].web_path_thumb2;
        };

    var foto_f = '<img src="'+ foto_mostrar_listview +'" alt="img25"/>';        


    if (sub.es_un == parent) {

                elements += '<li class="ui-li-has-thumb ui-first-child">'+ foto_f +'<h2>'+ subLoc + '</h2><h3>' + subLoc2 + '<h3><p>' + '</p><h6><h6><h1 class="ui-li-aside" style="right:0.80em">' + '<i class="fa fa-hashtag" aria-hidden="true"></i>'+ '<span class="notranslate">' + items + '<span></h1>' + '</li><a href="#popupPhotoPortrait" data-position-to="window" data-transition="fade" class="imagen-go" id="' + subLoc8 + '"><span class="fontawesome"><i class="fa fa-search-plus fa-3x" aria-hidden="true"></i></span></a></p>' 
                items++;  

    } //end if (sub.es_un)

});//$.each(data...)

$("#location-list").append($("<div/>").append($("<div/>", {
    "data-role": "collapsible", 
    "data-collapsed": "true", 
        "data-collapsed-icon": "carat-r", 
        "data-expanded-icon": "carat-d", 
        "class": parent,
        "style" : "margin : 8px 4px"  
}).append($("<h3/>").text(parent)).append($("<ul/>", { 
         "data-role": "listview", 
        "data-theme": "e",
        "data-count-theme": "b",
 }).append(elements).listview()))).collapsibleset('refresh');  

}); //$.each(seccion,...)


    }); //fin del getJSON files{}
    });  //fin del getJSON data[]

});// end ( document ).on

$('.imagen-go').click(function() {

        var id= $(this).attr("id"); 
        var extension =  ".jpg";
        document.getElementById('imagen-to-show').src = path_thumb1 + id + extension ;  // ori

}); // end ('.imagen-go')

JSON OUTPUT:专注于与上述代码相关的变量。来自1er JSON和2nd JSON

...
<!-- DIALOG page. Show picture. start -->

          <div data-role="dialog" id="popupPhotoPortrait" class="photopopup" data-overlay-theme="a"  data-corners="false" data-tolerance="30,15">
          <a href="#" data-rel="back" 
          class="ui-btn ui-corner-all ui-shadow ui-btn-a ui-icon-delete ui-btn-icon-notext ui-btn-left">Close</a>
          <img src="" alt="Foto del item" id="imagen-to-show" style="width: 100%">
          </div><!-- /Dialog --> 
...

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:放入$ .getJSON调用内部,检测显示图像的点击按钮的功能(从JSON获取“id”值)。

这里有最终的代码!!:

此致

$( document ).on( "pageinit", "#page-1", function( event ) {

var parser_origin = 'http://xxxxxx.com';
var path_thumb1 = '/upload_menus/thumb1/' + id_establecimiento() +'/';
var img_tmpl = '/upload_tmpl/upload.jpg';


   //get data[] (array). 1er JSON. start
    $.getJSON( parser_origin + "/_country/spain/v137/lacarte.restaurants.back/alacarte/php/r.shw.menu.php", { site: id_establecimiento(),idioma: to_translate(),traduccion: traduc_usada() }, function(data){

          for (var i=0, len=data.length; i < len; i++) {
              console.log(data[i]);
          }
              data = data['data']; 

    //get files{} (object) . 2nd JSON. start
    $.getJSON( parser_origin + "/_country/spain/v137/lacarte.restaurants.back/alacarte/php/r.shw.menu.php", { site: id_establecimiento(),idioma: to_translate(),traduccion: traduc_usada() }, function(files){ //files // ori

            for (var z=0, len=files.length; z < len; z++) {
              console.log(files[z]); //required!!
                }
            files = files['files']; 

// Now two nested $.each(), to iterate on 1st JSON and get objects of 2nd JSON. It`s work fine!

// 1st loop. sections 
$.each(data, function (i, v) {
collapsible.push(v.es_un); 

$.each(collapsible, function (i, v) {
    if ($.inArray(v, seccion) === -1) {
        seccion.push(v);
    }
    });
});

// 2nd loop. items into sections 
$.each(seccion, function (i, loc) {
var parent = loc;
var elements = '';

$.each(data, function (x, sub) {
    var subLoc = sub.nombre;
    var subLoc2 = sub.condimentos;
    var subLoc5 = sub.DT_RowId; 
    var subLoc6 = sub.alergeno; 
    var subLoc7 = sub.nota_item; 
    var subLoc8 = sub.image; 
    // check if have a picture  
      if  (subLoc8 == null || subLoc8 == '')   {
          var foto_mostrar_listview = img_tmpl;  // if not, assign a dummy image for not empty  
        }
      else if  (subLoc8 != null){// if, yes, get it 
          var foto_mostrar_listview = files.files_menus[subLoc8].web_path_thumb2;
        };

    var foto_f = '<img src="'+ foto_mostrar_listview +'" alt="img25"/>';        


    if (sub.es_un == parent) {

                elements += '<li class="ui-li-has-thumb ui-first-child">'+ foto_f +'<h2>'+ subLoc + '</h2><h3>' + subLoc2 + '<h3><p>' + '</p><h6><h6><h1 class="ui-li-aside" style="right:0.80em">' + '<i class="fa fa-hashtag" aria-hidden="true"></i>'+ '<span class="notranslate">' + items + '<span></h1>' + '</li><a href="#popupPhotoPortrait" data-position-to="window" data-transition="fade" class="imagen-go" id="' + subLoc8 + '"><span class="fontawesome"><i class="fa fa-search-plus fa-3x" aria-hidden="true"></i></span></a></p>' 
                items++;  

    } //end if (sub.es_un)

});//$.each(data...)

$("#location-list").append($("<div/>").append($("<div/>", {
    "data-role": "collapsible", 
    "data-collapsed": "true", 
        "data-collapsed-icon": "carat-r", 
        "data-expanded-icon": "carat-d", 
        "class": parent,
        "style" : "margin : 8px 4px"  
}).append($("<h3/>").text(parent)).append($("<ul/>", { 
         "data-role": "listview", 
        "data-theme": "e",
        "data-count-theme": "b",
 }).append(elements).listview()))).collapsibleset('refresh');  

}); //$.each(seccion,...)

// funtion that detect click on button (take "id" value from JSON)
$('.imagen-go').click(function() {

        var id= $(this).attr("id"); 
        var extension =  ".jpg";
        document.getElementById('imagen-to-show').src = path_thumb1 + id + extension ;  // ori

}); // end ('.imagen-go')

    }); //fin del getJSON files{}
    });  //fin del getJSON data[]

});// end ( document ).on