Peter Chung Peter Chung - 3 months ago 7
HTML Question

dynamically changing href address based on the response from the server

i am currently trying to create pagination feature. I am using bootstrap for css and jQuery.

There are total of 8 divs that contains a tags.

in my html file, i wrote

<div id="articleArea" class="row">
<div class="col-md-4 postTitle">
<a href="#">post title</a>
</div>
<div class="col-md-4 postTitle">
<a href="#">post title</a>
</div>
<div class="col-md-4 postTitle">
<a href="#">post title</a>
</div>
<div class="col-md-4 postTitle">
<a href="#">post title</a>
</div>
<div class="col-md-4 postTitle">
<a href="#">post title</a>
</div>
<div class="col-md-4 postTitle">
<a href="#">post title</a>
</div>
<div class="col-md-4 postTitle">
<a href="#">post title</a>
</div>
<div class="col-md-4 postTitle">
<a href="#">post title</a>
</div>
</div>


what I want to do is replacing each href in a tags, based on the response from my ajax call. I will just post success part of .ajax since other parts are completely functional and irrelevant to my question. my ajax call is returned in json format and var result is an array that contains 8 different hrefs that need to be assigned to each a tags in postTitle divs.

success: function(data){
var result = data["result"];
for(i=0; i < result.length; i++{
postTitle = result[i];
$(".postTitle.a").html(postTitle);
}
},


If i execute this code, a href are shown briefly but it disappears within a second. How can I fix this? and if there is better way to implement this feature, please do comment! Would love to be hear any feedbacks.

Answer

You need to run iteration over a tags instead of running iteration over results

$(".postTitle a").each(function(i) {
  postTitle = result[i];
  $(this).attr("href",postTitle);
});

This would run over each href tag and replace the values accordingly

EDIT: it should be .postTitle a

Comments