根据服务器的响应动态更改href地址

dynamically changing href address based on the response from the server

本文关键字:href 地址 动态 响应 服务器      更新时间:2023-09-26

我目前正在尝试创建分页功能。我正在使用css和jQuery的引导程序。

总共有8个div包含一个标记。

在我的html文件中,我写了

<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>

我想做的是根据ajax调用的响应替换标记中的每个href。我将只发布.ajax的成功部分,因为其他部分完全是功能性的,与我的问题无关。我的ajax调用以json格式返回,var结果是一个数组,其中包含8个不同的href,这些href需要分配给postTitlediv中的每个a标记。

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

如果我执行这个代码,href会短暂显示,但它会在一秒钟内消失。我该怎么解决这个问题?如果有更好的方法来实现这个功能,请发表评论!很乐意听到任何反馈。

您需要在标签上运行迭代,而不是在结果上运行迭代

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

这将在每个href标记上运行,并相应地替换值

EDIT:应为.postTitle a

您的选择器将选择的所有元素

$(".postTitle.a")

您应该选择每个标签并设置其href,此外它还缺少一个空格:

$(".postTitle a").each(function(index, value){
   $(value).attr('href', result[index]);
});
$(document).ready(function() {
    $('#pdf').change(function() {
      var newurl = $('#pdf').val();
      $('a.target').attr('href', newurl);
    });
});