jQuery快速填充非form数据

jQuery快速填充非form数据

先看看jQuery根据name填充form表单数据

html 复制代码
<!DOCTYPE html>
<html>

<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>

  <form id="myForm">
    <input type="text" name="username" />
    <input type="email" name="email" />
    <input type="password" name="password" />
  </form>

  <script>
    // 模拟数据
    const formData = {
      username: 'JohnDoe',
      email: 'johndoe@example.com',
      password: 'secretpassword'
    };

    // 填充表单
    $('#myForm input').each(function () {
      const inputName = $(this).attr('name');
      if (formData[inputName]) {
        $(this).val(formData[inputName]);
      }
    });
  </script>

</body>

</html>

按照相同的思路,渲染<span>

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
  <table>
    <tr>
      <td class="tbox03tdr" width="20%"><span prop="salesOrgName"></span></td>
      <td class="tbox03tdr" width="20%"><span prop="clientName"></span></td>
    </tr>
  </table>
  <script>
    // 发起 Ajax 请求
    $.ajax({
      url: 'yourDataUrl', // 替换为实际的后端数据接口 URL,这里假设为给定的 JSON 数据的模拟 URL
      method: 'GET',
      success: function (data) {
        // 获取具有 prop 属性的 span 元素
        const spans = $('span[prop]');
        // 遍历 span 元素并设置内容
        spans.each(function () {
          const propValue = $(this).attr('prop');
          $(this).html(data[propValue]);
        });
      },
      error: function (error) {
        console.error('Ajax 请求失败:', error);
      }
    });
  </script>
</body>

</html>

通过这样的方式,只要将span中定义prop属性和json中的key保持一致,即可填充数据

相关推荐
金融小师妹1 天前
AI算法视角下非农夜冲击波来袭,黄金高位区间震荡态势的深度神经网络解析
大数据·深度学习·1024程序员节
全栈小53 天前
【数据库】浙人医携手金仓数据库,打造全国首个多院区异构多活容灾架构
数据库·1024程序员节·金仓
CoderYanger5 天前
贪心算法:7.最长连续递增序列
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger5 天前
贪心算法:6.递增的三元子序列
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger5 天前
贪心算法:1.柠檬水找零
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger5 天前
贪心算法:4.摆动序列
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger5 天前
贪心算法:2.将数组和减半的最少操作次数
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger5 天前
贪心算法:8.买卖股票的最佳时机
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger5 天前
贪心算法:3.最大数
java·算法·leetcode·贪心算法·1024程序员节
CoderYanger5 天前
贪心算法:5.最长递增子序列
java·算法·leetcode·贪心算法·1024程序员节