jQuery cant access element with its attr href // simple tabs structure

故事扮演 提交于 2019-12-13 04:41:13

问题


I can't access "a" element with its href. Like this example, i need add class to element which got 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>​

I have tried each method but it didn't work. I need to access elements with their attr href and set the object to addClass or animate. This way returns me as a string.


回答1:


$('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');
});

You can also use an object mapping:

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

DEMO




回答2:


Use attribute selector like so:

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

Also note that you defined a takE variable and the you wrote take: probably you may want to write

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

   finD.addClass('thisisLink1');


来源:https://stackoverflow.com/questions/11048770/jquery-cant-access-element-with-its-attr-href-simple-tabs-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!