开发者

Jquery - Add a dynamic class to another DIV

OK, perhaps the title doesnt best explain what im trying to achive but if I can explain better hopefully开发者_如何学JAVA someone can help me out:

Im using the following code to select the text held within <a> and add it as the class of that element:

$(".nav a").each(function () {
  var self = $(this);
  self.addClass(self.text());
});

So for instance:

<a class="nav" href="page1.html">Google</a>
<a class="nav" href="page2.html">Yahoo</a>
<a class="nav" href="page3.html">Bing</a>

Becomes:

<a class="nav Google" href="page1.html">Google</a>
<a class="nav Yahoo" href="page2.html">Yahoo</a>    
<a class="nav Bing" href="page3.html">Bing</a>

Im using another bit of code to find out which page the user is currently on, either Google, Yahoo or Bing, and I then allocate another class of 'Selected'

e.g If i was on the Google page the <a> class becomes:

<a class="nav Google selected" href="page1.html">Google</a>

I would like to extend this a little further and can probably explain best via an example:

<a class="nav Google selected" href="page1.html">Google</a>
<a class="nav Yahoo" href="page2.html">Yahoo</a>    
<a class="nav Bing" href="page3.html">Bing</a>

<div class="container Google">

Lots of content

</div>

So as above, when 'Google' has the class 'selected' add that to <div class="container">, and the same for when the other links are clicked.

So in other words which ever <a> holds 'selected' add the previous class to <div class="container">

I know there are many ways to do this in far less 'hacky' ways but I have no other choice but to do it this way as I cannot edit the source of the page in anyway so it has to be a browser based solution rather than server side.


$('.nav').click(function(){
    $(this).addClass($(this).text());  // I believe you already do this.
    $('.conatiner').addClass($(this).text());
});


You can add the class to the container like this:

$('.conatiner').addClass($('a.selected').text());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜