[英]jquery .click() is not registering an event listener when I start my webpage
I have a simple HTML page and an accompanyish javascript file. 我有一个简单的HTML页面和一个随附的javascript文件。 I want to trigger some javascript code when the user clicks on an image in a table.
当用户单击表中的图像时,我想触发一些JavaScript代码。 I added a jquery .click() function and I call that also from document.ready, but when I load the page I cannot click on the image.
我添加了一个jquery .click()函数,我也从document.ready中调用它,但是当我加载页面时,无法单击图像。 If I open F12 and manually write the jquery .click(), it becomes enabled, the eventlistener is registered, and I can click on the image to trigger the code.
如果我打开F12并手动编写jquery .click(),它将启用,并注册事件侦听器,然后单击图像以触发代码。 But not when just loading the page from IntelliJ.
但不是仅从IntelliJ加载页面时。
Here is the HTML code: 这是HTML代码:
<html lang="en">
<head>
<h1>My page</h1>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="mainpage.css">
<script type="text/javascript" src="http_code.jquery.com_jquery-2.0.0.js"> </script>
<script type="text/javascript" src="profile.js" ></script>
</head>
<body>
<p>This is my main page</p>
<table>
<tr>
<td>
<div id="image1">
<img src="images/fluffcat.jpg" align="left"/>
</div>
</td>
<td><img src="images/midsommarcat.jpg" align="center" id="image2"/></td>
<td><img src="images/tortillacat.jpg" align="right" id="image3"/></td>
</tr>
<tr>
<td>Cat 1</td>
<td>Cat 2</td>
<td>Cat 3</td>
</tr>
</table>
</body>
</html>
and here is the javascript file: 这是javascript文件:
/**
* Created by jlg on 2016-06-11.
*/
function sayHello() {
console.log("Hello World")
}
function doClick() {
alert("something happened!");
window.open("Profile", "Profile", "", false);
}
function openPopup() {
console.log("I got here at least");
$("#image1").click(doClick);
}
function documentReadyFunctions() {
sayHello();
openPopup();
}
$( document ).ready(documentReadyFunctions());
What am I missing here? 我在这里想念什么? Is there some sort of ordering in the javascript file I'm missing?
我缺少的javascript文件中是否存在某种排序? The "console.log("I got here at least");"
“” console.log(“我至少到这里了”);“ shows up in the Console, as well as Hello World.
显示在控制台以及Hello World中。
In the following code, 在以下代码中,
$(document).ready(documentReadyFunctions());
documentReadyFunctions()
will call the function immediately and assign the returned value as callback to the ready
. documentReadyFunctions()
将立即调用该函数,并将返回值作为回调分配给ready
。
And as the script
is loaded in the <head>
, by the time when this function is executed, the elements are not available in the DOM. 并且,由于在执行此函数时将
script
加载到<head>
,因此元素在DOM中不可用。
Remove the ()
invocation of the function. 删除函数的
()
调用。
$(document).ready(documentReadyFunctions);
// ^^^^^^^^^^^^^^^^^^^^^^ // Don't call it, pass the function reference.
This will pass the function as reference and the function will be called when the DOM is ready. 这将传递该函数作为参考,并且在DOM准备就绪时将调用该函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.