Reputation: 11
I have a div
with id #id1
which contains links. Whenever I click on links, I make an AJAX call which also returns other links from server.
Now what I am doing is replacing the old links by new ones in #id1
using JQuery replaceWith()
method. By doing so, I maintain the id
of div
which is #id1
.
What I am trying to achieve here is get another bunch of links from server by clicking in those newly occupied links on div
with #id1
and continuously so.
Is it possible to write a script like that?
<div id = "id1">
<ul>
<li><a href ="test/show/1">link1</a></li>
<li><a href ="test/show/2">link1</a>link2</li>
....
</ul>
</div>
<script>
$('#id1 a').on(click, function(){
$.ajax({
url: '/test/test_now?page=' + page,
dataType: 'json',
success: function(response) {
$('#id1').repalceWith(response.links);
},
error: function() {
alert('An error occurred');
}
});</pre>
Upvotes: 0
Views: 73
Reputation: 410
As Pointy said, I think you need to be more specific, but I think is a job for templating, one of my favorites (for the small size) is Template7.
You create a template in a script tag like this in the foot of your html:
<script id="template" type="text/template7">
<ul>
{{#each links}}
<li>
<a href="{{url}}">{{text}}</a>
</li>
{{/each}}
</ul>
</script>
and then with jQuery or JS
var template = $('#template').html();
// compile it with Template7
var compiledTemplate = Template7.compile(template);
// Now we may render our compiled template by passing required context
var context = {
links:[
{text:'Text',url:'http://www.example.com'}
]
};
var html = compiledTemplate(context);
$('#id1').html( html );
You can include the context from wherever you want and each time you receive new links, just update the context and reuse the compiled template and replace the html again in your "#id1" div Just don't forget to include the Template7's js script file in your html
Regards
Upvotes: 1