3

click event handler on add button is not working if i do following(click event defined in add.js and ready event is present in index.js).

If i put click event handler and ready handler in index.js, click event works (alert popup).

Please help me.

Note: #add_button is a static button ( present in index.php, not a dynamic div, i tried live instead of click but that doesn't work too).

This doesn't work

<script src="js/index.js" type="text/javascript"></script>
<script src="js/add.js" type="text/javascript"></script>

index.js

$(document).ready(function() {
//code
});

add.js

$('#add_button').click(function(event){
 alert('hello');
});

this works if add.js content is directly put into index.js ?

$(document).ready(function() {
//code
$('#add_button').click(function(event){
 alert('hello');
});
});
4

4 回答 4

6

It's not because they're in different files. It's because the code hooking up the click event is running too soon. By putting the click setup inside ready, you're making it wait until "DOM ready". When it's not in the ready handler, it runs right away. If that code is above the #add_button element, the element won't exist yet, and the handler won't be hooked up.

You have two options:

  1. Just put the script tag for add.js below the element(s) it uses in the markup, e.g.:

    <input type="button" id="add_button" value="Add">
    <!-- ... -->
    <script src="add.js"></script>
    

    Then when the browser runs add.js, the element will exist. The script tag could even be immediately after the button, but I'd usually recommend the end of the file (e.g., just before the closing </body> tag), as indeed do the YUI folks.

  2. Use another ready handler in add.js (you can have as many as you like):

    // add.js gets its *own* ready handler
    $(document).ready(function() {
        $('#add_button').click(function(event){
         alert('hello');
        });
    });
    
于 2012-05-26T08:51:37.990 回答
2

将处理程序代码包装在 a.ready以及add.js. 这样,在您实际将处理程序附加到它之前,您可以确定 DOM 已准备好并且按钮存在。

这是一个速记.ready()

$(function() {
    $('#add_button').click(function(event){
       alert('hello');
    });
});
于 2012-05-26T08:52:40.033 回答
1

始终使用 document.ready 附加事件处理程序。外部js文件与html、css等导入数据同时处理。

于 2012-05-26T08:54:32.150 回答
1

index.js

function myClickEvent(event) {
 alert('hello');
}

添加.js

$(document).ready(function() {
$('#add_button').click(function(e){
      myClickEvent(e);
    });
    });

为什么你的逻辑不起作用?您正在尝试在文档的就绪状态内创建一个 self 函数,该函数不会在任何地方可用,因为它会在文档达到就绪状态时立即执行。

你必须在某个地方定义你的函数,你可以在任何你想要的地方引用它!最好的方法是始终将它们声明在顶部,并在文档就绪功能内部的任何地方使用。

$('#add_button').click([])由于有时在某些浏览器中您无法确定已加载的内容和未加载的内容,也可能无法正常工作!如果你把它也放在“准备好的”里面,你会做对的!它完美无缺!

于 2012-05-26T09:02:02.163 回答