2014-12-05 41 views
1

我很努力地提取我的div類,這是計劃成爲一個基本的asp.net網站上的選項卡。我希望通過jQuery來做到這一點,因爲這樣可以讓我在以後更多地控制動態函數。但是,當我嘗試獲取某個「selectedTab」的值時,我只是得到「undefined」。
我的問題是,我可以如何將相關類與該對象的名稱(我相信我的代碼已正確)一起存儲,然後再檢索它。在jQuery中訪問類屬性 - 鍵,值對

這是我非常簡單的HTML的相關部分:

<div id="t1" class="tabs"></div> 
<div id="t2" class="tabs"></div> 
<div id="t3" class="selectedTab"></div> 
<p></p> 

而且我的jQuery:

var tabMatchList = [{ 
    "tab1": "tabs" 
}, { 
    "tab2": "tabs" 
}, { 
    "tab3": "selectedTab" 
}]; 
$.each(tabMatchList, function (i, val) { 
    if ($("#t3").attr("class") == val[0]) { 
     $("p").append(i + " was the tab searched for"); 
    } else { 
     $("p").append(i + " was not the tab searched for." + val[0]); 
    } 
}); 

所有幫助和建議是非常值得歡迎的。

+1

'selectedTab'或'selectedTabs'?另外我假設你知道'tab1'和'tab2'將匹配't1'和't2'。 – Rhumborl 2014-12-05 09:00:04

+0

我知道它會匹配't1'和't2'。這是我的意圖。至於我在代碼中寫到的'selectedTabs'是一個錯字:P。 – 2014-12-05 09:11:01

回答

3

.attr("class")將返回類名沒有.,所以你需要從數組刪除:

而且,你的數組類selectedTab,但在你的HTML類是selectedTabs。確保它們匹配。

這且不說,你的代碼將無法正常工作是:

首先,我們需要你的對象的數組中的name屬性:

var tabMatchList = [{ 
    tabName: "tab1", tabClass: "tabs" 
    }, { 
    tabName: "tab2", tabClass: "tabs" 
    }, { 
    tabName: "tab3", tabClass: "selectedTab" 
}]; 

然後我們可以做到以下幾點:

$.each(tabMatchList, function (i, val) { 
    if ($("#t3").attr("class") == val.tabClass) { 
     $("p").append(" " + val.tabName + " was the tab searched for "); 
    } else { 
     $("p").append(" " + val.tabName + " was not the tab searched for."); 
    } 
}); 

DEMO

+0

這仍然不起作用。我在這裏添加了一個jFiddle,其中包含建議的更改:[鏈接](http://jsfiddle.net/vrcp78e8/) – 2014-12-05 09:05:53

+0

@ChristianS檢查我更新的答案我提供了一個演示,還有許多其他與您的代碼有關的問題,所以我稍微改寫了它。 – mattytommo 2014-12-05 09:10:53

+0

@ChristianS Demo在這裏:http://jsfiddle.net/8ocycjua/1/ – mattytommo 2014-12-05 09:12:15

0
$('#t1,#t2,#t3').each(function(i){ 
    if($(this).attr('class') == 'selectedTab'){ 
     $("p").append(i + " was the tab searched for <br/>"); 
    }else{ 
     $("p").append(i + " was not the tab searched for." + $(this).attr('class') + "<br/>"); 
    } 
}); 

DEMO