我的本地网站上的JavaScript出了点问题。我决定通过制作一个按钮来测试:
<button id="test">test</button>
并运行:
$('#test').click(alert("hello"));
问题是警报发生在我重新加载页面时,而不是在我按下按钮时。我在网站上运行了一些AJAX,还有一些PHP和基础知识(HTML,CSS,JS)。
$('#test').click( function() { alert("hello"); } );
function showWords(chooseDiv,str,table) {
if (str == "") {
document.getElementById(chooseDiv).innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(chooseDiv).innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getWords.php?filter="+str+"&table="+table,true);
xmlhttp.send();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="test">test</button>
更新
我附加了一个片段来显示此处有效但不适用于我的网站的代码。
将
警报包装到function () { alert (...); }
否则会立即触发
$('#test').click( function() { alert("hello"); } );
要正确附加此事件处理程序,您可以 1) 将其移动到 html 标记下方,最好在关闭</body>
标记之前,或者 2) 将其放入 jQuery DOM 就绪侦听器中,然后将其保留在页面上的任何位置(只要它低于jquery.js
本身),如下所示:
$(document).ready( function() {
$('#test').click( function() { alert("hello"); } );
});
在您的代码中,alert()
函数会立即运行。它与执行此操作相同:
var val = alert("hello"); // var val = undefined;
$('#test').click(val); // $('#test').click(undefined);
为了仅在单击元素时运行它,您需要将其放入回调函数中,如下所示:
$('#test').click(function () {
alert("hello");
});
您还可以将回调函数定义为"普通"函数,然后将其传递给 .click()
方法,如下所示:
function handleClick() {
alert("hello");
}
$('#test').click(handleClick);
回调函数仅在被调用时运行。在这种情况下,当用户单击元素时,.click()
方法将运行它。
为了将点击处理程序绑定到元素,Javascript需要在HTML之后运行。您应该做两件事:
将 jQuery 内容包装在以下内容中:
$(function () { // Put your jQuery code here... });
在页面底部包含您的 Javascript。这将确保您的 HTML 确实已加载,并且它具有使您的网站看起来加载速度更快的额外好处;Javascript文件停止网站的渲染,并将其放在底部可以防止这种情况。
<html> <head>...</head> <body> ... <script src="myscripts.js"></script> </body> </html>