我正在尝试在Bootstrap模式中创建一个表单。它应包含输入文件字段并预览所选图像,因此我可以使用Jcrop裁剪图像。
所以这就是我现在正在做的事情:
<script type="text/javascript">
$('#new-menu').on('shown.bs.modal', function (event) {
var modal = $(this);
var src = modal.find(".modal-body .upload");
var target = modal.find(".image");
src.bind("change", function () {
// fill fr with image data
modal.find(".jcrop-holder").remove();
readUrl(modal,target,src);
initJcrop(target);
});
});
function readUrl(modal,target,src){
if (src.files && src.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
target.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
initJcrop(target, modal);
}
else alert(src.files[0]);
}
}
function showCoords(c) {
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
}
function initJcrop(img) {
jcrop_api = $.Jcrop(img);
jQuery(img).Jcrop({
aspectRatio: 16 / 9,
onChange: showCoords,
setSelect: [0, 90, 160, 0],
onSelect: showCoords
}, function () {
modal.find(".jcrop-holder").css({
left: "50%",
marginLeft: -img.width / 2 + "px"
});
});
}
</script>
但是我得到了这个错误
'无法读取未定义'
的属性'0'
HTML
<form action="place/{id}/new/service/">
<div class="input-group">
<img src="http://placehold.it/160x90" class="image"/>
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">
<i class="glyphicon glyphicon-apple"></i>
</span>
<input type="text" id="form-name" class="form-control"
placeholder="Назва" value="" aria-describedby="basic-addon1"/>
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon2">
<i class="fa fa-tag"></i>
</span>
<input type="number" id="form-price" class="form-control"
placeholder="Ціна" value="" aria-describedby="basic-addon1"/>
<span style="padding:2px 5px" class="input-group-addon"><i>.грн</i></span>
</div>
<div class="input-group">
<textarea class="form-control place_description" style="resize: none" rows="5"
placeholder="Короткий опис послуги"></textarea>
</div>
<div style="text-align: center">
<small class="description-info">Залишилося 160 символів</small>
</div>
<div class="input-group">
<input type="file" class="upload"/>
</div>
<button id="new-service" class="btn btn-primary" type="submit">Зареєструвати</button>
</form>
答案 0 :(得分:4)
当您需要访问DOM元素时,传入src
的{{1}}是一个jQuery元素。有
function readUrl(modal,target,src)
而不是
src.get(0).files && src.get(0).files