简体   繁体   English

在外部 js 文件中引用 jQuery 事件处理程序

[英]Reference jQuery event handler in external js file

How do I use event handlers in jQuery when I have them in external files?当我在外部文件中有事件处理程序时,如何在 jQuery 中使用它们?

I'm using Phonegap to build an app, and for cleanliness sake, want to hold each jQuery function in a different js file.我正在使用 Phonegap 构建一个应用程序,并且为了清洁起见,希望将每个 jQuery 函数保存在不同的 js 文件中。

But when I try to click the button that the event handler is bound to, nothing happens.但是当我尝试单击事件处理程序绑定的按钮时,什么也没有发生。

The event isn't fired.该事件没有被触发。

I'm calling the js files after I load jQuery, just thought I'd say that.我在加载 jQuery 后调用 js 文件,只是想我会这么说。

External JS外部 JS

$("#getname").click(function()
{
        var youruname = localStorage.youruname;
            
        var PostData =
        {
            youruname: youruname,  
        };
        
        $.ajax
        ({
            url: "http://www.yellowcabsavannah.com/tag/tag_logout.php",
            type: "POST",
            data: PostData,
            async: false,
            dataType: 'json',
            cache: false,
            success: function(data)
            {
                //do stuff
            }
        });
    }
});

Main File JS主文件 JS

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript" src="tag.js"></script>
<script type="text/javascript" src="logout.js"></script>
<script src="http://jquery-ui-map.googlecode.com/svn/trunk/ui/min/jquery.ui.map.full.min.js"></script>

<div id="toolbar"><p>Who: <span id="name">Tap To Choose</span> - </p><a href='#' id="tag" class="mapbutton">Tag</a><br /><a href='#' id="logout" class='mapbutton'>Logout</a></div>

try by binding live or on尝试绑定 live 或 on

$("#getname").live('click',function(){...})
$(document).on('click',"#getname",function(){...})

Your html does not have an element with the id of getname .您的 html 没有 id 为getname的元素。 I am assuming you want to bind an event to the element with the id of name so try this:我假设您想将事件绑定到name为 id 的元素,因此请尝试以下操作:

$("#name").click(function() {

    alert("clicked");
});

Or change the span id from name to getname so或者将 span id 从name更改为getname所以

<span id="name">Tap To Choose</span>

becomes变成

<span id="getname">Tap To Choose</span>

and your event handler $("#getname").click should work just fine.并且您的事件处理程序$("#getname").click应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM