2014-03-24 27 views
0

我想從其他頁面定位鏈接中移除div id類。如何從其他頁面添加div類?

firstPage.html

<div class="question show" id="a1"> 
Sample 1 
</div> 

<div class="question" id="a2"> 
Sample 2 
</div> 

list.html

$(function() { 

      $("a").click(function() { 
       $("#a2").addClass('question show');     
      }); 


     }); 
    </script> 
</head> 
<body> 
<a href="firstPage.html#a1">Link 1</a> 
<a href="firstPage.html#a2">Link 2</a> 
</body> 

我想補充addClass('question show')類被點擊的DIV ID。

我想在這裏與Link1id=a1

But I'm failed to set class ('question show') help me to correct my code 請檢查代碼在這裏 http://plnkr.co/edit/fzdfjdrRbcWmir5wHcJW?p=preview

+1

更好的是你可以在[Plunker](http://plnkr.co) –

+0

中展示你的代碼a1已經有了這個類,試試'$(「#a2」).addClass('show');'那是你是什​​麼意思??令人困惑的措辭..也可以類有2個字? –

+2

@Jit,是的,'class'可以包含多個以空格分隔的類名稱 – freefaller

回答

2

我採取了不同的方法。我不會將此功能添加到list.html。使用該值調用頁面firstPage.html。我們將從firstPage.html中捕獲錨點。

另外,因爲你的所有div都有類'問題';我忽略了那個班,只針對'show'班。

因此,加載此功能與您的firstPage.html

$(document).ready(function(){ 
    var call = $(location).attr('href').split('#'); 
    var ancr = $.trim(call[1]); 
    if(ancr === undefined || ancr == ''){ 
     // Anchor not set, do nothing 
    } else { 
     if (!$('#'+ancr).hasClass('show')) { 
      $('#'+ancr).addClass('show'); 
     } 
    } 
}); 

我還假設你沒有用相同的ID多個div(一般不宜)。

我希望這會做你所需要的。

+0

謝謝你可以請更新它在小提琴這將是很好的幫助 – Neo

+1

小提琴有自己的網址,並將處理2頁棘手。你有沒有嘗試過提供的代碼?我所建議的對代碼非常簡單和輕微的編輯。從list.html中刪除你的js函數,並將我的js函數添加到firstPage.url中。就這樣。 – effone