2017-02-16 99 views
1

我一直在嘗試添加帶有功能的內容。當我點擊錨點時應該添加具有相同錨點ID的內容,我認爲這個邏輯是正確的,但沒有任何事情發生。有沒有更好的方法來解決這個問題。來自ID的呼叫功能

$('.tab a').click(function(){ 
 
    var tabAnchor = $(this).attr('href'); 
 
    
 
    if($(tabAnchor)=='#info'){ 
 
    callInfo(); 
 
    } 
 
    else if($(tabAnchor)=='#category'){ 
 
    callCategory(); 
 
    } 
 
    
 
}) 
 

 

 
function callInfo(){ 
 
    $('#info').append('<p>Info has been added</p>') 
 
} 
 

 
function callCategory(){ 
 
    $('#info').append('<p>Category has been added</p>') 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<ul class="tab"> 
 
    <li><a href=#info>info</a></li> 
 
    <li><a href=#category>category</a></li> 
 
</ul> 
 

 
<div id="info"> 
 

 
</div> 
 

 
<div id="category"> 
 

 
</div>

+0

使用html()而不是追加 –

+2

'if($(tabAnchor)=='#info')'?你正在比較一個字符串的jQuery對象... – Andreas

回答

4

問題是你if聲明,你比較jQuery對象爲一個字符串 - 這將永遠不會返回true。相反,你應該琴絃直接比較,這樣的:

$('.tab a').click(function() { 
 
    var tabAnchor = $(this).attr('href'); 
 
    if (tabAnchor == '#info') { 
 
    callInfo(); 
 
    } else if (tabAnchor == '#category') { 
 
    callCategory(); 
 
    } 
 
}) 
 

 
function callInfo() { 
 
    $('#info').append('<p>Info has been added</p>') 
 
} 
 

 
function callCategory() { 
 
    $('#info').append('<p>Category has been added</p>') 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<ul class="tab"> 
 
    <li><a href="#info">info</a></li> 
 
    <li><a href="#category">category</a></li> 
 
</ul> 
 

 
<div id="info"></div> 
 
<div id="category"></div>

另外請注意,您可以進行邏輯更簡單,更易於維護由具有執行基於邏輯的單一功能點擊的href

$('.tab a').click(function() { 
 
    var tabAnchor = $(this).attr('href'); 
 
    $(tabAnchor).append('<p>' + tabAnchor.substring(1) + ' has been added</p>') 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<ul class="tab"> 
 
    <li><a href="#info">info</a></li> 
 
    <li><a href="#category">category</a></li> 
 
</ul> 
 

 
<div id="info"></div> 
 
<div id="category"></div>

+0

我看到了,我想當我創建變量仍然需要$符號來比較字符串。 – rnDesto

+0

根本沒有。在JS中,'$'前綴根本沒有內在含義。這只是一個命名約定,表示一個包含jQuery對象的變量 –