第一次尝试加载ajax数据时javascript的奇怪行为

时间:2016-12-14 02:33:28

标签: javascript php jquery html ajax

我有一个页面(shop.php)在DIV点击,我做一个覆盖弹出窗口,我从另一个PHP页面(detail.php)加载ajax数据,如下所示:

shop.php的HTML:

<div class="box-item2" 
 style="background:url(<?=$img_path?>); 
        background-size:cover;
        background-position: 50% 50%; 
        overflow:hidden;
        width:100%; height:420px; "

onclick="clicked(this);"

id="<?=$prod_id?>">


    <div class="overlay">&nbsp;</div>
    <span class="txtover">VIEW DETAILS</span>
</div>  

shop.php的MY JS功能:

function clicked(div) {

   var id = div.id;
   $("#overlay3-content").html("");
   $.ajax({
       type: "GET",
       url: "detail.php",   
       data: {id: id},
       dataType: "html",   //expect html to be returned                
       success: function(response){                    
           $("#overlay3-content").html(response); 
            }
      });

   $("#overlay3").css("display", 'block').css("opacity", '1');
   $("#mask").css("display", 'block').css("opacity", '1');
   $("#container_close").css("display", 'block').css("opacity", '1');
}

执行此操作时,没有问题,Overlay Popup可以很好地加载来自detail.php的代码。

但是,在detail.php中,我使用另一个javascript函数来更改缩略图点击时的div背景图像。 JS代码如下:

来自detail.php里面的JS CODE

$('.image_thumb').click(function(){

  var url = $(this).attr("id");
  $('#image_main').css('background-image', 'url(url)');
});

我的问题。 当我第一次加载我的页面shop.php(刷新后),我点击一个DIV并弹出窗口打开,但是里面的JS功能(detail.php)点击一个缩略图来改变背景图像不起作用。

如果我退出叠加弹出窗口(没有刷新),并重新打开叠加弹出窗口,则在detail.php上使用JS函数来更改背景图像。

似乎我需要打开弹出窗口,关闭它,然后重新打开它以使其正常工作,我不知道为什么。如果我通过直接转到detail.php来尝试我的代码(绕过shop.php的加载弹出过程),那么它就可以立即运行。没问题

所以看起来负载弹出在第一次尝试执行JS的详细信息时缺少一些东西.php

有什么想法吗?感谢

2 个答案:

答案 0 :(得分:1)

只是一个猜测,但尝试这样:

&#13;
&#13;
$(document).on('click', '.image_thumb', function(){
  var url = $(this).attr("id");
  $('#image_main').css('background-image', 'url(url)');
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我发现了自己的错误。不知何故,我在我的detail.php页面中出现了这个问题。

一旦我删除它,一切正常