我正在尝试使用javascript获取和设置图像src,但我一直收到这个错误:
uncaughtTypeError:无法读取null的属性“src”。
我已搜索Stackoverflow,但找不到解决方案。这是我的密码
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modalBody">
<img src="" id="modalImg">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<script>
function viewProduct(product_id){
var request = new XMLHttpRequest();
request.open('GET', '/view_product_details/?product_id=' + product_id, true);
request.onreadystatechange = function(){
if (this.status == 200 && this.readyState == 4){
var data = JSON.parse(this.responseText);
console.log(data);
document.getElementById('exampleModalLongTitle').innerHTML = data.name
document.getElementById('modalBody').innerHTML = data.description
document.getElementById('img').setAttribute('src', data.image_url)
document.getElementById('img').src = data.image_url}}
request.send();}
</script>
1条答案
按热度按时间w7t8yxp51#
您没有任何id为
img
的元素。唯一的图像对象的id为mn1o1p,那么您的getElementById应该是: