【问题标题】:Create selector with id from ajax jquery使用来自 ajax jquery 的 id 创建选择器
【发布时间】:2022-08-18 20:24:00
【问题描述】:

我正在从我的 ajax 调用中接收 id 和链接。我必须使用 id 来找到我的 tr,然后在 td 中显示带有 class .center-xs 的链接

她是我的 HTML 代码:

...

<thead>
    <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Sport</th>
        <th>My Link</th>
    </tr>
</thead>

<tbody>
    <tr id=\"abc\">
        <td>Jons</td>
        <td>15</td>
        <td>Football</td>
        <td class=\"center-xs\"></td>
    </tr>
    <tr id=\"def\">
        <td>Tom</td>
        <td>20</td>
        <td>Football</td>
        <td class=\"center-xs\"></td>
    </tr>
    <tr id=\"ghi\">
        <td>Harry</td>
        <td>14</td>
        <td>Football</td>
        <td class=\"center-xs\"></td>
    </tr>
</tbody>
...

她是我的 Ajax 电话:

...

$.ajax({
            url: \'/url/Letter\',
            type: \'post\',
            cache: true,
            data: JSON.stringify({ letter: data }),
            contentType: \"application/json; charset=utf-8\",
            success: function (res) {
            $(\'#\' + res.Id + \'\').closest(\".center-xs\").html(\'<a href=\"\' + res.Link + \'\">Open link</a>\');


            }
        });

...

  • 如有疑问,请查看文档 - .closest()向上文档树 - 您希望 .find() 查看 tr 的子级。
  • 仅供参考+ \'\' 没用

标签: jquery ajax dynamic server jquery-selectors


【解决方案1】:

.find(顺着DOM树走),不是.closest(顺着DOM树走)

而且您的引号有点奇怪-模板文字更易于使用/阅读

const res = { Id : "def", Link:"https://google.com" };
$(`#${res.Id}`).find(".center-xs").html(`<a href="${res.Link}">Open link</a>`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Sport</th>
      <th>My Link</th>
    </tr>
  </thead>

  <tbody>
    <tr id="abc">
      <td>Jons</td>
      <td>15</td>
      <td>Football</td>
      <td class="center-xs"></td>
    </tr>
    <tr id="def">
      <td>Tom</td>
      <td>20</td>
      <td>Football</td>
      <td class="center-xs"></td>
    </tr>
    <tr id="ghi">
      <td>Harry</td>
      <td>14</td>
      <td>Football</td>
      <td class="center-xs"></td>
    </tr>
  </tbody>
</table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-11
    • 2013-01-19
    • 2013-12-13
    • 2013-02-02
    • 2012-12-07
    • 2014-04-03
    • 2012-05-04
    • 1970-01-01
    相关资源
    最近更新 更多