2011-07-10 81 views
1

我相信這個答案很簡單,我剛纔已經弄清楚了。使用jquery變量來識別一個div類/ Id

我有一個簡單的點擊功能,它適用於被點擊的列表中的任何鏈接。當點擊一個人時,我希望它刪除一個div上的一個類,它與其中一個鏈接屬性相關。 E.g:

// The link 
<li><a href="#" title="example1">example1</a></li> 

// The div 
<div id="example1" class="selected"></div> 

這是有點事,我已經試過了,但它是不是正確的:

$("ul.switcher a").click(function(e){ 
e.preventDefault(); 
$("#" + $(this().val).removeClass("selected"); 
}); 

任何幫助,將不勝感激!如果任何人也可以告訴我這樣做的JavaScript等價物,這將是一個不錯的獎金!

回答

3

那麼你接近:

$("ul.switcher a").click(function(e){ 
e.preventDefault(); 
$("#" + this.title).removeClass("selected"); 
}); 

對於這樣的事情,HTML5的「數據 - 」屬性約定可以非常方便。你會改變的標記如下:

<li><a href="#" data-targetId="example1">example1</a></li> 

然後在你的代碼,你可以使用jQuery的「數據()」方法:

$("ul.switcher a").click(function(e){ 
e.preventDefault(); 
$("#" + $(this).data('targetId')).removeClass("selected"); 
}); 

這種技術可以讓你避免‘超載’等屬性,就像你對「標題」所做的一樣。 (當然這並不是一件壞事,但有時候你可能希望「標題」是有意義的東西,因爲當鼠標位於元素上時,它將顯示出來)。

+0

知道這將是簡單的 - 謝謝你的幫助! 'this.title'是否也適用於標準的JavaScript? –

+0

是的,'this.title'中沒有jQuery - 記住jQuery **是** JavaScript是非常重要的 - 它只是一組基於stock語言核心的函數,它不會改變任何有關語言結構的普通功能。 – Pointy

3

變化

$("#" + $(this().val).removeClass("selected"); 

$("#" + this.title).removeClass("selected"); 

做是因爲原始DOM對象的title屬性反映了 「title」 屬性。 HTML5規範草案中的here,以及更多DOM2 HTML規範中的here

+0

也可以使用'的.text()'假設它是相同的則有不需要額外的屬性或「發送」標題。 –

0

試試這個, 呼叫你的鏈接點擊(使用jQuery的一樣)下面的JavaScript功能,

 function removeClass() 
    { 
     if ($('#example1').hasClass('selected')) //Will check whether the div has the mentioned class. 
     { 
       $('#example1').removeClass('selected'); //This will remove the specified class from the div. 
     } 
     else 
     { 
      $('#example1').addClass('class1'); //This can be used to add a class to the div. 
     } 
     } 

希望這有助於...