如何将.click()事件添加到图像? [英] How do I add a .click() event to an image?
问题描述
根据 Jose Faeti ,我有一个基于鼠标点击的图像脚本。现在我需要帮助添加一个.click()事件到下面的代码,以便当用户点击图像时,它执行脚本中显示的功能。
I have a script that places an image based on a mouse click thanks to Jose Faeti. Now I need help adding a .click() event to the code below so that when a user clicks the image it performs the function shown in the script.
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()
我把整个代码放在下面,以防你想看到它。
I put the entire code below, in case you want to see it.
<html>
<head>
<script language="javascript" type="text/javascript">
<!--
document.getElementById('foo').addEventListener('click', function (e) {
var img = document.createElement('img');
img.setAttribute('src', 'http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png');
e.target.appendChild(img);
});
// -->
</script>
</head>
<body>
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()
</body>
</html>
帮助?
推荐答案
首先,这行
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()
你混合HTML和JavaScript。它不行。摆脱 .click()
。
You're mixing HTML and JavaScript. It doesn't work like that. Get rid of the .click()
there.
如果你阅读了你在那里的JavaScript, code> document.getElementById('foo')它正在寻找一个ID为 foo
的HTML元素。你没有一个给你的图像ID:
If you read the JavaScript you've got there, document.getElementById('foo')
it's looking for an HTML element with an ID of foo
. You don't have one. Give your image that ID:
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
或者,您可以将JS放在一个函数中,并将一个单击放在你的HTML中:
Alternatively, you could throw the JS in a function and put an onclick in your HTML:
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" onclick="myfunction()" />
我建议您尽量阅读JavaScript和HTML。
I suggest you do some reading up on JavaScript and HTML though.
其他人是正确的,需要将JS $绑定以外的< img>
。
The others are right about needing to move the <img>
above the JS click binding too.
这篇关于如何将.click()事件添加到图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!