将JQuery Click事件附加到定位ID [英] Attach JQuery Click Event to Anchor Id

查看:64
本文介绍了将JQuery Click事件附加到定位ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的SO.为什么我不能直接将点击事件附加到锚点ID?我应该指出,我也在使用JQuery Mobile.

I have an easy one SO. Why cant I attach a click event straight to an anchors Id? I should have pointed out that I am also using JQuery Mobile.

            <div id="foobarNavbar" data-role="navbar" style="display:none;">
                <ul>
                    <li><a id="foo" href="#foo" data-icon="plus">New Event</a></li>
                    <li><a id="bar" href="#bar" data-icon="grid">Events</a></li>
                </ul>
            </div><!-- /foobarNavbar-->

我正在尝试将一个点击事件附加到foo.这不起作用:

I am trying to attach a click event to foo. This doesn't work:

        $('#foo').bind('click', function(e) 
        {   
            e.preventDefault();
            console.log("You clicked foo! good work");
        });

这确实有效,但是给了我foo和bar的click事件.是否无法绑定到锚ID或我是菜鸟错误?

This does work but gives me the click event for both foo and bar. Is it not possible to bind to an anchor Id or am I making a rookie error?

        $('#foobarNavbar ul li a').bind('click', function(e) 
        {   
            e.preventDefault();
            console.log("You clicked foo! good work");
            console.log(e);
        });

推荐答案

重要提示:请使用$(document).bind('pageinit'),而不要使用$(document).ready()

Important: Use $(document).bind('pageinit'), not $(document).ready()

您在jQuery中学习的第一件事是在$(document).ready()函数,以便一切都将在DOM已加载.但是,在jQuery Mobile中,Ajax用于加载在导航时将每个页面的内容放入DOM中,并准备好DOM处理程序仅对第一页执行.在以下情况下执行代码加载并创建新页面后,可以绑定到pageinit事件.此事件在页面底部详细说明.

The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate, and the DOM ready handler only executes for the first page. To execute code whenever a new page is loaded and created, you can bind to the pageinit event. This event is explained in detail at the bottom of this page.

我试图使用文档就绪而不是pageinit进行绑定.第一个功能

I was trying to bind using document ready instead of pageinit. The first function

$('#foo').bind('click', function(e) 
        {   
            e.preventDefault();
            console.log("You clicked foo! good work");
        });

移至'pageinit'事件时,效果很好.但是,我仍然不确定为什么第二个代码示例有效,而第一个代码示例无效.

works fine when moved to the 'pageinit' event. I am still not sure, however, why the second code example worked but not the first.

这篇关于将JQuery Click事件附加到定位ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆