如何使 createElement('IMG') 可点击?
How does one make createElement('IMG') clickable?
我的目标是使创建的元素底部 Queen 与顶部 Queen 一样可点击。如何做到这一点?
<!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>
只需添加:
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>
我的目标是使创建的元素底部 Queen 与顶部 Queen 一样可点击。如何做到这一点?
<!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>
只需添加:
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>