【问题标题】:How does one make createElement('IMG') clickable?如何使 createElement('IMG') 可点击?
【发布时间】:2015-09-13 22:24:12
【问题描述】:

我的目标是使底部皇后,一个创建的元素,可点击与顶部皇后相同。如何做到这一点?

<!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>

【问题讨论】:

标签: click createelement setattribute event-listener


【解决方案1】:

只需添加:

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

你的属性。

    <!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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2013-03-07
    相关资源
    最近更新 更多