weixin_33749131 2012-02-09 15:43 采纳率: 0%
浏览 32

jQuery事件未触发

I've this piece of markup. This piece has been loaded through ajax and appended inside a div.

Content of file user-bar.php:

<div id="u-bar">
    <ul id="u-nav" class="nav">
        <li id="notifications-list" class="dropdown" data-time="" >
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">
            <i class="icon-comment"></i>
            Notifications
            <b class="caret"></b>
            </a>
            <ul class="dropdown-menu" >
                <li><a href="#">Notification One</a></li>
                <li><a href="#">Notification two</a></li>
                <li class="divider"></li>
                <li><a href="#">Show All Notifications</a></li>
            </ul>
        </li>
        <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">
            <i class="icon-user"></i>
            Profile
            <b class="caret"></b>
        </a>
        <ul class="dropdown-menu">
            <li><a href="#">View Profile</a></li>
            <li><a href="#">Settings</a></li>
        </ul>
    </li>
    <li><a href="php/logout.php">Logout</a></li>
    <div class="clear"></div>
    </ul>
</div>

I've scripts.js file as below which is included in the index.php file as <script type="text/javascript" src="js/scripts.js"></script>

$(function(){
    loadUserBar();

    $('#notifications-list').live('click', function(){
        console.log('Test');
        $('#notifications-list .icon-comment').removeClass('new');
    });
});

function loadUserBar(){
     $('#user-area').load('php/user-bar.php', function(){
         initBootstrapElems(); //Initializing All popover elements
     });    
}

index.php file has the div#user-area where the ajax returned markup is inserted.

After the whole page has been loaded, when I click on the list-item #notifications-list, nothing happens. But when I typed in $('#notifications-list').click() directly in the console, the log does appears and the removeClass does occur.

What could be wrong here?

  • 写回答

2条回答 默认 最新

  • weixin_33728268 2012-02-09 15:56
    关注

    Try to put the handler for click on the a tag event.

    $('#notifications-list a').live('click', function(){ ... })
    

    Update: You can't use the same id for all li tags. You need to change the li.#notifications-list to a class if you have that on each tag and then update the js:

    $('.notifications-list a').live('click', function(){ ... })
    
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧