【问题标题】:Cannot get click event on appended anchors无法在附加的锚点上获得点击事件
【发布时间】:2012-06-07 12:30:17
【问题描述】:

我确信这与 clone() 有关,但我在上面找不到任何东西。我的问题是我正在添加一些带有锚点的 HTML。这些锚点应该响应 click() 然后开始一个 ajax 调用。我似乎无法阻止锚点默认事件处理 $('.term a')。

(function($) { 
$(document).ready(function() {
var item = '#main-menu li';
var http_addy = 'http://windowsdeveloper.loc';
// voacabulary id is set in the menu. If one is found then load the terms to the   menu
$('*[id*=vocabulary]:visible').each(function() {
            var voc_id = $(this).attr('id').split('-');
            var parent_li = $(this).parent('[class^=menu-]');
            $.get(http_addy + '/category/content/term_list/' + voc_id[1], function(data) {
                    $(parent_li).append(data);
            });
     });
   // use this to get the terms nodes
    $('div.term a').click(function(event){
            var url = $(this).attr('href');
            $.get(url, function(data) {
                    $('#term-nodes').append(data);                      
            });
            return false;
    });

    $(item).mouseenter(function(event){
        // Styles to show the box
            $(this).children('.vocabulary').show();
        }       
    );
    $('.navigation').mouseleave(
        function() {
            $('#main-menu li').children('.vocabulary').hide();
        }
    );
});
})(jQuery);



<ul id="main-menu" class="links inline clearfix main-menu">
<li class="menu-1050 first">
<a id="vocabulary-3" href="/newsarticletopics/windowsdeveloper">Articles</a>
<div id="term-nodes"></div>
<div id="voc-3" class="vocabulary" style="display: none;">
<div id="term-12" class="term">
    <a href="/category/content/term_nodes/12">Serien</a>
</div>
</div>
</li>

【问题讨论】:

    标签: jquery drupal


    【解决方案1】:

    这是因为您正在动态加载一些内容并更新 DOM。你应该使用 jQuery on 像这样绑定你的点击事件

    // use this to get the terms nodes
    $(document).on("click",".term a",function(event){
            event.preventDefault();
            var url = $(this).attr('href');
            $.get(url, function(data) {
                    $('#term-nodes').append(data);                      
            });           
    });
    

    jQuery on 适用于 DOM 中当前和未来的元素。 on 从 jQuery 1.7+ 开始可用。如果您使用的是旧版本,则应考虑live

    【讨论】:

    • @CarlAdamMcDade:欢迎。很高兴我能帮上忙。
    【解决方案2】:
    $("selector").on("click", function(e){
    
     // Do some code here
    
    });
    

    如果你使用的是旧版本的 jQuery,你可以使用 .delegate()

    $("selector").delegate("click", function(e){
    
      // .delegate() takes the parameters a bit differently i think , correct me if i am wrong
     // Do some code here
    
    });
    

    Event binding on dynamically created elements?

    【讨论】:

      猜你喜欢
      • 2012-06-28
      • 1970-01-01
      • 2011-11-12
      • 2011-08-13
      • 2016-06-02
      • 2021-10-02
      • 2011-07-23
      • 2013-12-28
      • 2016-09-13
      相关资源
      最近更新 更多