Decapitar Decapitar - 4 years ago 109
Javascript Question

Appending div from another html file

hi guys 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"

and 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 appens a div but it doesnt reset it just keeps spamming the same div over and over and over how can i stop it?

Answer Source

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 your DOM, 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)); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download