Reputation: 259
I've been trying to add content with function. When I click anchor should be adding content with same anchor ID, I'm thinking this logic is right, but nothing is happen. Is there any better way to get this right.
$('.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>
Upvotes: 1
Views: 1572
Reputation: 337713
The issue is your if
statement where you compare a jQuery object to a string - this will never return true. Instead, you should compare the strings directly, like this:
$('.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>
Also note that you can make the logic much simpler and easier to maintain by having a single function that performs the logic based on the clicked 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>
Upvotes: 4