[英]How do I add a .click() event to an image?
感謝Jose Faeti ,我有一個基於鼠標點擊放置圖像的腳本。 現在我需要幫助將 .click() 事件添加到下面的代碼中,以便在用戶單擊圖像時執行腳本中顯示的功能。
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()
我把整個代碼放在下面,以防你想看。
<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()
。
如果您閱讀了 JavaScript, document.getElementById('foo')
它正在尋找 ID 為foo
的 HTML 元素。 你沒有。 為您的圖片提供該 ID:
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
或者,您可以將 JS 放入一個函數中,然后在您的 HTML 中放置一個 onclick:
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" onclick="myfunction()" />
不過,我建議你閱讀一些 JavaScript 和 HTML。
其他人也需要將<img>
移動到 JS 單擊綁定上方是正確的。
您不能在元素存在之前將事件綁定到元素,因此您應該在onload
事件中執行此操作:
<html>
<head>
<script type="text/javascript">
window.onload = function() {
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 id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
</body>
</html>
將<img>
括在<a>
標簽中。
<a href="http://www.google.com.pk"><img src="smiley.gif"></a>
它將在同一選項卡上打開鏈接,如果您想在新選項卡上打開鏈接,請使用 target="_blank"
<a href="http://www.google.com.pk" target="_blank"><img src="smiley.gif"></a>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script type="text/javascript" >
function openOnImageClick()
{
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
var img = document.createElement('img');
img.setAttribute('src', 'tiger.jpg');
img.setAttribute('width', '200');
img.setAttribute('height', '150');
document.getElementById("images").appendChild(img);
}
</script>
</head>
<body>
<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>
<div id="images" >
</div>
<img src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
<img src="Logo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.