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保持一致,即可填充数据

相关推荐
lzb_kkk14 天前
【实习总结】Qt通过Qt Linguist(语言家)实现多语言支持
开发语言·c++·qt·1024程序员节·qt linguist·qt 语言家
Yangy_Jiaojiao22 天前
三维手眼标定
1024程序员节
guozhetao24 天前
【图论,拓扑排序】P1347 排序
数据结构·c++·python·算法·leetcode·图论·1024程序员节
lzb_kkk1 个月前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
lzb_kkk2 个月前
【MFC】编辑框、下拉框、列表控件
c语言·开发语言·c++·mfc·1024程序员节
lzb_kkk2 个月前
【MFC】树控件的使用详解
开发语言·c++·windows·mfc·1024程序员节
SizeTheMoment3 个月前
List介绍
1024程序员节
开利网络3 个月前
产业互联网+三融战略:重构企业增长密码
大数据·运维·服务器·人工智能·重构·1024程序员节
wei_shuo3 个月前
从数据中台到数据飞轮:实现数据驱动的升级之路
1024程序员节·数据飞轮
玖剹4 个月前
矩阵区域和 --- 前缀和
数据结构·c++·算法·leetcode·矩阵·动态规划·1024程序员节