[英]Why is my jQuery click function not firing?
I am building a search page that posts back to itself. 我正在构建一个搜索页面,该页面可以发回自身。 I finally got a sample page working here .
我终于在这里工作了一个示例页面 。 I also built a fiddle here .
我也在这里摆了一个小提琴 。 But I don't understand why it works.
但是我不明白为什么会起作用。 When the user initially hits the page, it should only show the search form.
当用户最初点击页面时,它应该仅显示搜索表单。 When a search is submitted, it should hide the form, show results, and a button for a new search.
提交搜索后,它应该隐藏表单,显示结果以及用于新搜索的按钮。 I'm using jQuery.
我正在使用jQuery。 Here's my code:
这是我的代码:
//Code Block 1
// Show search form if there is no querystring
//Hide search form, show results if querystring
$(document).ready(function() {
if(document.location.search.length) {
$("#newsearch").show(1000);
$("#results").show(1000);
$("#search").hide(300);
} else {
$("#search").show();
}
});
//code block 2
//if new search clicked, show form, hide results
$("#newsearch").click(function() {
$("#newsearch").hide(1000);
$("#results").hide(1000);
$("#search").show(300);
});
When code block 1 and 2 are loaded in the head, block 2 never fires. 将代码块1和2装入磁头时,块2永远不会触发。 When I pull 2 out and put it at the end of the page, it works.
当我拉出2并将其放在页面末尾时,它可以工作。
I am trying to learn, so I have 2 questions. 我正在尝试学习,所以我有2个问题。 (1) Why didn't it work when it was one block, and (2) Any suggestions for doing it better?
(1)当它只有一个街区时为什么不起作用,以及(2)有什么建议可以做得更好?
Thank you. 谢谢。
D d
$("#newsearch").click(function() {
is being run before the #newsearch
element exists. $("#newsearch").click(function() {
正在#newsearch
元素存在之前运行。
Therefore the click event is attached to nothing. 因此,单击事件不附带任何内容。
It works in the first block because it's in a $(document).ready
, which runs code inside only after everything has finished loading. 它在第一个块中起作用,因为它在
$(document).ready
,仅在完成所有加载后才在内部运行代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.