通过单击事件将背景图像添加到div。

通过单击事件将背景图像添加到div。

问题描述:

大家好,通过单击事件将背景图像添加到div。

我正在建立一个4x4的盒子DIVS网格。这个网格是用一个循环构建的,它为每个div分配类,ID,图像日期和事件监听器。这是记忆游戏的一部分。

var cards_shown = 0; 
var memoryCards = [ 
    { 
     id: 1, 
     name: 'Horde Emblem', 
     logo: 'horde.png', 
     showing: false 
    }, 
    { 
     id: 2, 
     name: 'Orc Emblem', 
     logo: 'orc.png', 
     showing: false 
    }, 
    { 
     id: 3, 
     name: 'Troll Emblem', 
     logo: 'troll.png', 
     showing: false 
    }, 
    { 
     id: 4, 
     name: 'Tauren Emblem', 
     logo: 'tauren.jpg', 
     showing: false 
    }, 
    { 
     id: 5, 
     name: 'Forsaken Emblem', 
     logo: 'dead.gif', 
     showing: false 
    }, 
    { 
     id: 6, 
     name: 'Blood Elf Emblem', 
     logo: 'belf.png', 
     showing: false 
    }, 
    { 
     id: 7, 
     name: 'Goblin Emblem', 
     logo: 'goblin.png', 
     showing: false 
    }, 
    { 
     id: 8, 
     name: 'Pandaren Emblem', 
     logo: 'panda.png', 
     showing: false 
    } 
]; 

function layoutCards(){ 
    for (var i=0; i < 16; i++) { 
     var genDiv = document.createElement('div'); 
     genDiv.setAttribute('id', 'memoryCard' + (i+1)); 
     genDiv.setAttribute('class', 'memoryCard'); 
     genDiv.setAttribute('data-imageId', i) 

     genDiv.addEventListener('click', function(e) { 
      showCard(e) 
     }); 

     document.getElementsByTagName('div')[0].appendChild(genDiv); 

     if ((i+1) % 4 == 0) { 
      var newBr = document.createElement('br'); 
      document.getElementsByTagName('div')[0].appendChild(newBr); 

     } 
    } 
} 



function showCard(e){ 
    cards_shown += 1 
    document.getElementByClassNames('memoryCard').style.backgroundImage = "url('img/" + memoryCards[i].logo + "')"; 

HTML

<!DOCTYPE HTML> 
<html> 
<head> 
    <title></title> 

    <link rel="stylesheet" href="css/styles.css"> 
</head> 
<body> 
    <div class="container"> 

</body> 
<script type="text/javascript" src="js/main.js"></script> 
</html> 

点击任何的div的应导致图像的外观通过拉动memoryCards.logo对象信息和将其放入的类或ID div作为背景风格。

我得到一个控制台错误,它指出document.getElementByClassNames不是showCard函数和HTMLDivElement的函数。线。我将尝试使用getElementByID,并尝试以接收每个生成的div的修改的id标记的方式传递参数。

它读取这样的:

Uncaught TypeError: document.getElementByClassNames is not a function 
    at showCard (main.js:98) 
    at HTMLDivElement.<anonymous> (main.js:81) 
showCard @ main.js:98 
(anonymous) @ main.js:81 

反馈将是有益的,匿名的通话功能给了我很多的麻烦。

它看起来像你有一个额外的's'末尾className。将其更改为

document.getElementsByClassName('memoryCard').... 
+0

感谢您的反馈意见。我最终尝试了一些其他的东西,我认为这是因为现在我得到了一个不同的错误。 我使用'e.target.style.backgroundImage'代替,但我得到一个错误,说[i]没有定义,出于某种原因。 –