简体   繁体   English

jQuery .click事件未向类注册

[英]jQuery .click event not registering with class

I'm trying to register a click event for a menu list button identified by a class, but it doesn't seem to be firing. 我正在尝试为一个类标识的菜单列表按钮注册一个click事件,但是似乎没有触发。 My code is as follows: 我的代码如下:

<body>
<!-- jQuery Simple Drop-Down Menu http://javascript-array.com/scripts/jquery_simple_drop_down_menu/# -->
        <div id="dropDownDiv" style="width: 908px; height: 24px; margin: auto auto; background: #324143;">
            <ul id="jsddm">
                <li><a href="#">Item 1</a>
                    <ul>
                        <li><a class="btn myOtherClass" href="#">Button 1</a></li>
                        <li><a class="btn myOtherClass"href="#">Button 2</a></li>
                    </ul>
                </li>
                <li><a href="#">Item 2</a>
                    <ul>
                        <li><a class="btn myOtherClass" href="#">Button 3</a></li>
                        <li><a class="btn myOtherClass" href="#">Button 4</a></li>
                    </ul>
                </li>
            </ul>
        </div>

</body>

And in my script I have the following: 在我的脚本中,我有以下内容:

/* Register the click event for menu buttons */
$('.btn').click(function () { 
    alert("You clicked a button"); 
  });

The alert never fires and I'm not sure why, any help is appreciated. 该警报永远不会触发,我不确定为什么会有所帮助。

UPDATE: 更新:

The code in the link works for me to, not sure why it's not working in my project. 链接中的代码对我有用,不确定为什么在我的项目中不起作用。 I'm in an Eclipse PHP Project environment with Java resources enabled. 我在启用Java资源的Eclipse PHP Project环境中。 I tried my project in Chrome and Firefox, not working for either. 我在Chrome和Firefox中尝试了我的项目,但两者都不起作用。 I'll check the rest of my script. 我将检查脚本的其余部分。

UPDATE 2: 更新2:

Looks like Shef's recommendation about wrapping in a .ready function did the trick. 看起来Shef关于使用.ready函数包装的建议成功了。 I still don't understand why it needs that to work, "c=smiles"'s link worked without it. 我仍然不明白为什么需要它才能起作用,“ c = smiles”的链接在没有它的情况下也起作用。

Works fine for me, check it out . 对我来说很好, 请检查一下 Maybe you didn't include jQuery? 也许您没有包括jQuery? Or, you are not wrapping your event listener bind code inside a document ready like this: 或者,您没有将事件侦听器绑定代码包装在准备就绪的文档中,如下所示:

$(document).ready(function(){
    $('.btn').click(function () { 
        alert("You clicked a button"); 
    });
});

are you using stopPropagation or return false in another click event that may have prevented the click event from happening? 您是使用stopPropagation还是在另一个可能阻止click事件发生的其他click事件中返回false?

Is the jQuery used after jQuery has been loaded? 加载jQuery后是否使用jQuery?

Is the in the DOM at the time of binding? 绑定时在DOM中吗? (use delegate instead of click if not, or bind after loading) (如果不是,请使用委托而不是单击,否则请在加载后绑定)

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

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