如何使createElement(' IMG')可点击?

时间:2015-06-26 21:01:39

标签: click createelement setattribute event-listener

我的目标是使底部女王,一个创造的元素,可点击与顶级女王相同。如何实现这一目标?

<!DOCTYPE html>
<html>
<body>
<p><button onclick='createAnImg()'>Create Card</button></p>
<img src='Card Deck/QueenHearts.png' onclick='alert("You picked the Queen of Hearts!")'>
<p id='card_holder'></p>

<script>
function createAnImg() {
x = document.createElement('IMG');
x.setAttribute('id', 'Queen_of_Hearts');
x.setAttribute('src', 'Card Deck/QueenHearts.png');
x.setAttribute('width', '72');
x.setAttribute('alt', 'Card Face');
document.getElementById('card_holder').appendChild(x);
}
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

只需添加:

x.setAttribute('onclick', 'alert("You picked the Queen of Hearts!")');

到您的属性。

&#13;
&#13;
    <!DOCTYPE html>
    <html>
    <body>
    <p><button onclick='createAnImg()'>Create Card</button></p>
    <img src='https://lh3.googleusercontent.com/-KBSwW1xXPt4/VY12U034XEI/AAAAAAAAASE/5C_uZ_o64QE/s96/23.png' onclick='alert("You picked the Queen of Hearts!")'>
    <p id='card_holder'></p>
    
    <script>
    function createAnImg() {
    x = document.createElement('IMG');
    x.setAttribute('id', 'Queen_of_Hearts');
    x.setAttribute('src', 'https://lh3.googleusercontent.com/-KBSwW1xXPt4/VY12U034XEI/AAAAAAAAASE/5C_uZ_o64QE/s96/23.png');
    x.setAttribute('width', '72');
    x.setAttribute('alt', 'Card Face');
    x.setAttribute('onclick', 'alert("You picked the Queen of Hearts!")');
    document.getElementById('card_holder').appendChild(x);
    }
    </script>
    
    </body>
    </html>
&#13;
&#13;
&#13;