javascript - jQuery 没有正常运行,立即打印警报

标签 javascript php jquery html ajax

我的本​​地网站上的 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"); } );
});

关于javascript - jQuery 没有正常运行,立即打印警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35690029/

相关文章:

javascript - 无法使用 Node 下载 S3 对象

javascript - 我如何在 Angular Directive(指令)中绑定(bind)模型

php - MySQL 表 : Display every row with criteria met

jquery - 如何转换为 jquery 数据表

javascript - 导航跟随滚动

javascript - Canvas - 如何同时制作多个图像的动画?

javascript - AngularJS - TD 元素中标题属性中的多个 {{ }}

PHP mysql 连接3个表并在正确的位置显示正确的信息

php - 如何回显所有行和所有列?

javascript - JSON.parse 返回意外标记