javascript - jquery 中的加载函数行为如何

标签 javascript jquery html

我有 html 代码和 jquery 来根据加载或未加载的图像显示和隐藏表单,如下所示

...
<title>Untitled Document</title>
</head>
 <script type="text/javascript" src="bootstrap/js/jquery.js"></script>
            <script type="text/javascript">
$(document).ready(function(){

$("#image11")
.load(function(){
    alert('oke1');
    $("#upload1").hide();
    $("#image21").hide();

})
.error(function(){
    alert('oke2');
    $("#image11").hide();
    $("#upload1").hide();
    $("#image21")
        .load(function(){
            alert('oke3');
            $("#upload1").hide();

            $("#image11").hide();
    })
    .error(function(){
        alert('oke4');
            $("#upload1").show();
            $("#image21").hide()
            $("#image11").hide();
      });
   });

})

            </script>
 <body>
     <div class="col-sm-5 col-xs-7">
     <img src="foto_peserta/tes.jpg" width="100"   id="image11"  alt="tes"/>
     <img src="foto_peserta/cek.jpg" width="100" id="image21"  alt="tes2"/>          
  </div>
<div id="upload1">
<form method="post" name="form1" action="<?php echo  $editFormAction; ?>"  enctype="multipart/form-data"><img id="previewHolder"  alt="Foto" width="100px" height="100px"/> <p>
   <input type="file" name="foto_peserta" id="foto_peserta"  required>
   <p class="help-block">maximum image size is 50 kB,only JPG, JPEG, PNG &amp; GIF files are allowed</p>
   <button type="submit" class="btn btn-success">Upload Foto</button>
              <input type="hidden" name="MM_update" value="form1" >
              <input type="hidden"  name="id_personal" value="<?php echo $row_foto_peserta_tampil['id_personal']; ?> ">
    </form></div>


 </body>
 </html>

我只是困惑为什么每次刷新页面时(当我的 image21 已加载而我的 image11 未加载时)警报 ('oke2') 提示但不是 alert('oke3 '),我的代码有什么问题吗?

最佳答案

自 jQuery 1.8 以来,您正在谈论的加载函数已被弃用:

在以后的版本中,jQuery 中只保留了一个 .load() 函数,为了避免歧义,它用于从另一个源加载数据http://api.jquery.com/load/例如,如果您需要将来自服务器的文本加载到页面的 div 中。

您可以使用以下命令检查图像是否加载

$('img.mustLoad').on('load',function(){
        /* Fire your image resize code here */
});

这个非常复杂的片段取 self 上面发布的问题的当前第二个答案,因此归功于“Alex W”。这应该适用于每个版本的 jQuery

要处理加载错误,您需要使用单独的事件

$('img.mustLoad').on('error',function(){
        /* Fire your image resize code here */
});

因此您需要相应地编辑代码

关于javascript - jquery 中的加载函数行为如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32807035/

相关文章:

javascript - "+var === +var"在内部如何工作以验证 var 是否为数字?

javascript - 在 AJAX 处理程序中下载文件

javascript - jquery 绑定(bind)到选择更改

在网页上仅使用 JavaScript 上传文件

html - 添加内容后 div 对齐失败

javascript - 为什么这个 onchange 事件不起作用?

javascript - 将多项选择作为与选择框分隔的逗号分隔到文本输入中

javascript - 在 React 中切换布局同时保持状态

javascript - 调用多个元素的分页不起作用,仅调用最后一个元素

javascript - 主选项卡需要仅使用 html、css 和 javascript 嵌套的子选项卡