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>