2012-07-25 37 views
0
<span class="here one-two-del-del other1">test</span> 
<span class="here one-two-aaa o2ther">test</span> 
<span class="here one-two-dsf other3">test</span> 
<span class="here one-two-213 o4ther">test</span> 
<span class="here one-two-sdf other5">test</span> 
<span class="here one-two-sdff o6ther">test</span> 

<span class="set one-two-aaaa">set 1</span> <br /> 
<span class="set one-two-bb-fff">set 2</span> <br /> 
<span class="set one-two-vcvc">set 3</span> <br /> 
<span class="set one-two-fgdfg-dfgfd-fgf">set 4</span> <br />​ 

​$('.set').click(function(){ 
    $('#here').??? 
})​ 

我想 - 如果我點擊.set,那麼這應該得到自己的類,並在所有.here中取代。用jQuery修改課程

例如,如果我點擊集2那麼所有的跨度類。這裏應該是:

​<span class="here one-two-bb-fff other1">test</span> 
<span class="here one-two-bb-fff o2ther">test</span> 
<span class="here one-two-bb-fff other3">test</span> 
<span class="here one-two-bb-fff o4ther">test</span> 
<span class="here one-two-bb-fff other5">test</span> 
<span class="here one-two-bb-fff o6ther">test</span> 

我不能使用removeClass,因爲我不知道如何爲當前的類。如果我使用.attr(「類」,「新」),那麼這全部替換類,但我還必須有一流的其他1,o2ther等

http://jsfiddle.net/NNhDd/

也許我必須使用正則表達式?

+3

有幾個類的屬性,使您的文檔_invalid_。 – undefined 2012-07-25 08:14:06

+0

你不需要多個'class'屬性[檢查這個](http://webdesign.about.com/od/css/qt/tipcssmulticlas.htm)。 – Vishal 2012-07-25 08:15:00

+0

不是有效的標記。您不能再多使用一次class屬性。 – 2012-07-25 08:16:09

回答

2

HTML

<span class="here one-two-del-del other1">test</span> 
<span class="here one-two-aaa o2ther">test</span> 
<span class="here one-two-dsf other3">test</span> 
<span class="here one-two-213 o4ther">test</span> 
<span class="here one-two-sdf other5">test</span> 
<span class="here one-two-sdff o6ther">test</span> 

<br /> 

<span class="set one-two-aaaa">set 1</span> <br /> 
<span class="set one-two-bb-fff">set 2</span> <br /> 
<span class="set one-two-vcvc">set 3</span> <br /> 
<span class="set one-two-fgdfg-dfgfd-fgf">set 4</span> 

的JavaScript

$('.set').click(function() { 
    var replaceWith = $(this).attr('class'); 
    // Remove the "set " from replaceWith 
    replaceWith = replaceWith.replace(/set ?/g, ''); 

    $('.here').each(function() { 
     var newClass = $(this).attr('class'); 
     newClass = newClass.replace(/one-two-[^ $]+/, ''); 
     newClass = newClass + ' ' + replaceWith; 
     // Now set the new class 
     $(this).attr('class', newClass); 
    }); 
}) 

這裏有一個小提琴:http://jsfiddle.net/NNhDd/3/

+0

完美,非常感謝:) – 2012-07-25 08:33:39