上传文件的input框的change时间只能触发一次的原因

xiaoxiao2021-02-28  6

html代码:

<tr>     <td><label for="pic" style="font-weight:normal;">图片</label>:</td>     <td colspan="3">         <div class="file-box">             <input type="text" maxlength="50" value="<?PHP echo $threadinfo['pic']?>" name="pic" style="display:inline-block;width:200px;" class="form-control" id="pic">             <a href='JavaScript:;' class="upload" style="display:inline-block;width:60px;" οnclick="click_up()">上传</a>             <div style="display:none"><input type="file" id="upload" name="UploadForm[file]" /></div>         </div>     </td> </tr>

<?=Html::jsFile('/static/admin/js/ajaxfileupload.js')?>

js代码1 [有bug:点击上传一次图片后,再次点击上传图片无效:原因input框的change事件只触发了一次]

这个问题并不是由change事件失效造成的,而是ajaxFileUpload插件造成的,它会把原来的file元素替换成新的file元素,所以之前绑定的change事件就失效了,需要重新绑定一下

<script>

$("input#upload").change(function () {         $.ajaxFileUpload({             url: "/index.php?r=public/upload/upload",             secureuri: false,             data:{'type':'forum','cid':<?php echo intval($threadinfo['cid'])?>},             fileElementId:'upload',             dataType: 'json',             success: function (data, status) {                 if (data && data.result == 'Success') {                     $("#pic").val(data.url);                     $("#pic_show").attr('src',data.url);                     return ;                 }else{                     alert("上传失败");                     return ;                 }             },             error: function (data, status, e) {                 return;             }         });     });

</script>

js代码2[解决办法,再次点击上传时给input框重新绑定change事件]

<script> function click_up(){     $("input#upload").click();       //添加一个点击事件来触发$(input#upload)的change事件     $("input#upload").change(function () {         $.ajaxFileUpload({             url: "/index.php?r=public/upload/upload",             secureuri: false,             data:{'type':'forum','cid':<?php echo intval($threadinfo['cid'])?>},             fileElementId:'upload',             dataType: 'json',             success: function (data, status) {                 if (data && data.result == 'Success') {                     $("#pic").val(data.url);                     $("#pic_show").attr('src',data.url);                     return ;                 }else{                     alert("上传失败");                     return ;                 }             },             error: function (data, status, e) {                 return;             }         });     }); }     </script>

原文:http://blog.csdn.net/qq_34625397/article/details/53811940

转载请注明原文地址: https://www.6miu.com/read-450164.html

最新回复(0)