附加到页面外的点击事件 [英] Attach to click event outside page
问题描述
我的ASPX页面中有以下按钮-
I have the following button in my ASPX page -
$('#btnHello').click(function () {
alert('Hi there');
});
这将按预期工作并显示警报,但是我想以完全相同的逻辑将此事件移到我的 global.js 文件中.我在ASPX页面的顶部引用了此文件,但是该事件未触发.我该如何实现?
Which works as expected and presents the alert, however I want to move this event into my global.js file with the exact same logic. I am referencing this file at the top of my ASPX page however the event is not firing. How can I achieve this?
推荐答案
一开始,您正在执行的是一个函数:
What you're executing is a function, at the very beginning:
$('#btnHello').click(function () {
alert('Hi there');
});
您要将警报功能连接到元素#btnHello
.
You're hooking up your alert function to the element #btnHello
.
但是在执行时,尚未加载#btnHello
.它尚不存在.所以什么也不会发生.
But at the time it executes, #btnHello
hasn't been loaded. It doesn't exist yet. So nothing gets hooked up.
您可以通过在最后执行您的代码来解决此问题,或者(更可靠的是,我认为)将代码的执行推迟到文档完成加载为止:
You can get around this either by executing your code at the very end, or (more reliably, I think) deferring this code's execution until the document has finished loading:
$(function () {
$('#btnHello').click(function () {
alert('Hi there');
});
});
您可以将其放在global.js中,但是直到页面完全加载后它才执行.
You would put this in your global.js, but it wouldn't execute until your page is completely loaded.
这篇关于附加到页面外的点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!