Reputation: 89
I have 2 menu buttons which supposed to append divs from an external html. Now I have this:
<ul>
<li><a href="#" onclick="javascript:test2();" value="#CS" >CS</a></li>
<li><a href="#" onclick="javascript:test2();" value="#PS" >PS</a></li>
</ul>
And 2 divs on the external html, that just have simple text in them saying "text1" and "text2".
I use this code to append the data:
$.get('external/list.html', function (data) {
$(data).filter('#PS').appendTo('#content')
});
How can I "upgrade" it to take for example an attribute like value, and use it to choose what div to append? Because I prefer to have it as 1 function instead of making 2.
Also this code appends a div, but it doesn't reset it. It just keeps spamming the same div over and over and over. How can I stop it?
Upvotes: 2
Views: 870
Reputation: 29683
Option 1
Keep a single call to your $.get
, as you are doing now, but pass reference of your clicked element
through your function
as below:
<ul>
<li><a href="#" onclick="javascript:test2(this);" value="#CS" >CS</a></li>
<li><a href="#" onclick="javascript:test2(this);" value="#PS" >PS</a></li>
</ul>
JS
function test2(ctrl)
{
var element=$(ctrl).attr('value');
$.get('external/list.html', function (data) {
$(data).filter(element).appendTo('#content');
//element will have value either #PS or #CS
});
}
Note -
.appendTo
will keep on appending the data to yourDOM
, instead use.html
which replaces contents everytime
Ex:
$(data).filter(element).html('#content');
Option 2
You can also attach click
event to your a
tags with a common class given for both thus removing inline function
call as below:
<ul>
<li><a href="#" value="#CS" class="menu">CS</a></li>
<li><a href="#" value="#PS" class="menu">PS</a></li>
</ul>
JS
$(".menu").on('click',function(){
var element=$(this).attr('value'); //this refers to clicked element
$.get('external/list.html', function (data) {
$(data).filter(element).appendTo('#content');
//element will have value either #PS or #CS
});
});
Update
Ideally html
should work but I imposed it in wrong way. You just need to change one thing as below:
$("#content").html($(data).filter(element));
Upvotes: 1