我想设置src来动态地在我的脚本中添加图像,用户首先浏览他的图像,并在文本字段中输入他的名字,然后点击添加按钮,然后动态添加一个表格行。如何阅读我的图片的网址?
因为我想显示图像。我的脚本中是否有错误?
$(document).ready(function() {
$('#addbtn').click(function() {
var val = $.trim($('#txt-val').val());
var some = $('#imagefile').val();
if (val != '') {
//$('#imagepath').attr('src','+some+');
$("imagefile").change(function() {
readURL('#imagefile');
});
$('#newval').append('<option>' + val + '</option>');
$('#list-tbl').append('<tr height=\"50\">' + '<td>' + val + '<img id=\"imagepath\" src="#" style="width:50px; height:50px;"/>' + '</td>' + '<td>' + val + '</td>' + '</tr>');
}
$('#txt-val').val('');
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imagepath')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
});
.dynamictbl {
width: 100%;
height: auto;
}
table,
tr,
td {
border: 1px solid #dddddd;
border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="imagefile" onchange="readURL(this);" />
<input type="text" style="width:150px;" id="txt-val" />
<button id="addbtn">Add</button>
<select id="newval" style="width:150px;"></select>
<div style="width:100%; height:300px; margin-top:5px; overflow:auto;">
<table id="list-tbl" class="dynamictbl">
<tr height="50">
<th width="50%">Index Of Entry<span id="img"></span>
</th>
<th width="50%">User Name</th>
</tr>
</table>
</div>
我看到一个错误:变化$( “镜像文件”)改变(函数(){为$( “#镜像文件”),变化(函数(){希望。这有助于你 – Vermicello
**只是一个提示:**使用[URL.createObjectURL(blob)](https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL)而不是 – Endless