使用两个变量从javascript中以HTML格式显示图像

时间:2017-12-01 14:43:47

标签: javascript html image

我想在文件的html页面中显示一张卡片。我试图从两个数组中获取两个随机选择的值,然后将它们连接在一起以创建图像的src。当我尝试这样做时,我不断收到此错误:

未捕获的TypeError:无法将属性'src'设置为null     在blackJack.js:14

HTML代码

<!DOCTYPE html>
<html lang ='en'>
<head>
<meta charset="UTF-8">
<script src="blackJack.js"></script>
<title>Section 2: Javascript Language Basics</title>
</head>

<body>
<h1>Section 2: Javascript Language Basics</h1>

<img id="myImg" src="/Users/victorcollins/Desktop/Computer Science/IA/Coding/Playing Cards/PNG-cards-1.3/2spades.png" width="107" height="98">
</body>



</html>

的Javascript

var suits, cards, players, randCards, randSuit;

suits = ['hearts', 'diamonds', 'spades', 'clubs'];
cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
players = [];

randCards = Math.floor(Math.random() * 13) + 1;
var randSuit = suits[Math.floor(Math.random() * suits.length)];
image = randCards + randSuit;
console.log(randCards+randSuit);
console.log(image);

document.getElementById("myImg").src = '/Users/victorcollins/Desktop/Computer Science/IA/Coding/Playing Cards/PNG-cards-1.3'+image+'.png';

1 个答案:

答案 0 :(得分:0)

  

未捕获的TypeError:无法在null处设置null的属性'src'   blackJack.js:14

您必须先将元素加载到DOM中才能访问它,因此请在结束正文标记之前放置此脚本标记。

EntityObject