【问题标题】:jquery: add #hash to all links if it doesn't already have one?jquery:将#hash 添加到所有链接,如果它还没有?
【发布时间】:2011-02-25 14:39:16
【问题描述】:

大家好, 以下代码工作正常...我正在向#wpf-wrapper 内部的所有链接添加#wpf-wrapper 哈希。

$('#wpf-wrapper a').live('click',function() {
    $(this).attr('href', $(this).attr('href') + "#wpf-wrapper");        
});

但是,如果有一个已经有的链接,例如href="#"我不想再添加一个。为什么以下代码不起作用?

$('#wpf-wrapper a').not('#wpf-wrapper a[href="#"]').live('click',function() 
    $(this).attr('href', $(this).attr('href') + "#wpf-wrapper");        
});

我的链接突然都没有添加这个#wpf-wrapper?

【问题讨论】:

  • 您是否有理由希望在点击处理程序中而不是在前面执行此操作?

标签: jquery hash add


【解决方案1】:

这个选择器错误

$('#wpf-wrapper a').not('#wpf-wrapper a[href="#"]')

应该使用 attribute contains selector 和适当的 :not() 选择器

$('#wpf-wrapper a:not([href*="#"])')

【讨论】:

    【解决方案2】:

    这是另一种方式:

    $('#wpf-wrapper a').each(function(){ 
        if( !this.hash ) this.hash = "#wpf-wrapper";
    });
    

    您可以使用a 元素上的原生hash 属性来设置它,而不是使用jQuery 的.attr() 方法。


    如果您在点击处理程序中执行此操作的原因是 .each() 不起作用,那么您很可能在加载 DOM 之前运行代码。

    如果是这样,请执行以下操作:

    $(function() {
        $('#wpf-wrapper a').each(function(){ 
            if( !this.hash ) this.hash = "#wpf-wrapper";
        });
    });
    

    如果您要动态创建元素,请在创建它们时添加哈希。

    【讨论】:

      猜你喜欢
      • 2011-05-17
      • 1970-01-01
      • 2011-08-02
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-05
      相关资源
      最近更新 更多