jquery绑定多个锚点 [英] jquery bind on multiple anchor

查看:75
本文介绍了jquery绑定多个锚点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将同一事件绑定到锚链接列表。为什么这不起作用?

I would like to bind the same event to a list of anchor link. Why this does not work?

加价:

<a tabindex="0" href="#contactRoles" 
    class="fg-button fg-button-icon-right ui-widget ui-state-default ui-corner-all" 
    id="contactAdd">
    <span class="ui-icon ui-icon-triangle-1-s"></span>Aggiungi contatto</a>

<div id="contactRoles" class="hidden">
<ul>
    <li><a href="#1" class="contactRole">Cliente</a></li>
    <li><a href="#2" class="contactRole">Controparte</a></li>
    <li><a href="#3" class="contactRole">Avvocato</a></li>
    <li><a href="#4" class="contactRole">Avv. Controparte</a></li>
    <li><a href="#5" class="contactRole">Altre parti</a></li>
    <li><a href="#6" class="contactRole">Domiciliatario</a></li>
    <li><a href="#7" class="contactRole">Pubblico Ministero</a></li>
    <li><a href="#8" class="contactRole">Giudice</a></li>
    <li><a href="#9" class="contactRole">Istruttori</a></li>
    <li><a href="#10" class="contactRole">Studio Legale</a></li>
</ul>
</div>

jQuery:

$('#contactAdd').menu({
    content: $('#contactRoles').html(),
    width: 150,
    showSpeed: 300
});

$("a.contactRole").click(function(event){
    event.preventDefault();
    alert("Link " + $(this).attr("href") + " clicked");
});

我哪里错了?

编辑
@everybody:是的,脚本用$(文件)包装.ready(...)

EDIT: @everybody: Yes the script is wrapped by a $(document).ready(...)

进一步信息认为隐藏类隐藏的div是隐藏的,只能通过点击另一个锚点来查看,如此截图所示。

For further information consider that the div with class "hidden" is hidden and can only be viewed by a click on another anchor as you can see from this screenshot.

推荐答案

编辑:根据您的评论,您已经使用 ready()函数进行了包装。

Based on your comment, you're already wrapped with a ready() function.

另一种可能性是在页面加载后, a.contactRole 元素被添加到DOM 中。

Another possibility is that the a.contactRole elements are added to the DOM after the page loads.

如果是这种情况,试试这个:

If that's the case, try this:

$(function() {
    $("a.contactRole").live('click', function(event){
        event.preventDefault();
        alert("Link " + $(this).attr("href") + " clicked");
    });
});






原始答案:

应该有效。在分配点击处理程序之前,您是否确定已加载文档?

Should work. Have you made sure the document is loaded before assigning the click handler?

如果< a> 元素避风港当您尝试分配处理程序时,它将无法运行。

If the <a> elements haven't loaded when you try to assign the handler, it won't work.

示例: http://jsfiddle.net/kjSG8/

   // Wrap your code with $(function() {...}) to make sure it doesn't
   //    run until the DOM is fully loaded
$(function() {
    $("a.contactRole").click(function(event){
        event.preventDefault();
        alert("Link " + $(this).attr("href") + " clicked");
    });
});

这篇关于jquery绑定多个锚点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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