我有 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 & 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/