【问题标题】:jQuery cant access element with its attr href // simple tabs structurejQuery 无法通过 attr href 访问元素 // 简单的选项卡结构
【发布时间】:2012-06-18 09:52:15
【问题描述】:

我无法通过其 href 访问“a”元素。像这个例子一样,我需要将类添加到获得 href="#one"

的元素

Here is jsFiddle.

jQuery:

//tabs part is working fine
$('.tabs').hide();
$('.tabs:first').show();
$('ul li a').click(function(){
   var target = $(this).attr('href');
    $('.tabs').hide();
    $(target).fadeIn(500);

   $('ul li a').removeClass('selected');
   $(this).addClass('selected');
});

   //problem starts when i try to reach href
   var link1 = '#one';
   var link2 = '#two';
   var link3 = '#three';

   var takE = $('ul li a').each();
   var finD = take.attr('href');
   finD.addClass('thisisLink1');​

html:

<ul>
    <li><a href="#one">Home</a></li>
    <li><a href="#two">Posts</a></li>
    <li><a href="#three">About</a></li>
</ul>
<div class="tabs" id="one">Home Container</div>
<div class="tabs" id="two">Posts Container</div>
<div class="tabs" id="three">About Container</div>​

每种方法我都试过了,但没有奏效。我需要使用 attr href 访问元素并将对象设置为 addClass 或 animate。这种方式将我作为字符串返回。

【问题讨论】:

    标签: javascript jquery tabs selector href


    【解决方案1】:

    像这样使用属性选择器:

    $('a[href="#one"]').addClass(...)
    

    还请注意,您定义了一个 takE 变量并且您编写了 take:可能您可能想要编写

       var takE = $('ul li'),
           finD = takE.find('a[href="#one"]');
    
       finD.addClass('thisisLink1');
    

    【讨论】:

    • 我正在编写一个插件,需要将其设置为变量。像 var link1 = '#one'; $('a[href=link1]').addClass(...)
    • ('a[href="#one"]') 我可以将“#one”部分设置为变量吗?
    【解决方案2】:
    $('ul li a').each(function() {
      if(this.href == link1) $(this).addClass('thisisLink1');
      if(this.href == link2) $(this).addClass('thisisLink2');
      if(this.href == link3) $(this).addClass('thisisLink3');
    });
    

    您还可以使用对象映射:

     var links = {
        '#one': 'thisislink1',
        '#two': 'thisislink2',
        '#three': 'thisislink3',
    };
    $.each(links, function(key, val) {
        $('ul li a[href="' + key + '"]').addClass(val);
    });
    

    DEMO

    【讨论】:

    • $('ul li a[href="' + key + '"]') 这部分可能有用,我正在尝试 atm
    • 是的,对象映射方法很好用,非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 2014-02-19
    相关资源
    最近更新 更多