使用jQuery动态生成html时附加文本

时间:2017-09-07 11:56:08

标签: jquery html

我有这个HTML。我需要根据某些条件.append某些文字:

1)td.name a包含text which triggers append

2)td.nametd.quantity位于同一行

3).append仅在同一行td.nametd.quantity中完成。

有多行。行没有类和代码是动态生成的 - 每行可能最终在表中的不同位置。我该如何定位



if (jQuery('tbody tr td.name a:contains("text which triggers append")').length > 0) {
    jQuery('tbody tr td.quantity').append('<span>text to append</span>');
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<tbody>
    <tr>
        <td class="name"><a>text which triggers append</a></td>
        <td class="quantity">quantity</td>
    </tr>
    <tr>
        <td class="name"><a>other text</a></td>
        <td class="quantity">other quantity</td>
    </tr>
</tbody>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

尝试

jQuery('tbody tr td.name a:contains("text which triggers append")').closest('tr').find('td.quantity').append('<span>text to append</span>');

&#13;
&#13;
 jQuery('tbody tr td.name a:contains("text which triggers append")').closest('tr').find('td.quantity').append('<span>text to append</span>');
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<table border="1">
<tbody>
    <tr>
        <td class="name"><a>text which triggers append</a></td>
        <td class="quantity">quantity</td>
    </tr>
    <tr>
        <td class="name"><a>other text</a></td>
        <td class="quantity">other quantity</td>
    </tr>
</tbody>
<table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用解决方案

&#13;
&#13;
$('table tbody tr').each(function(){
  $(this).find('td.name').each(function(){
    if($(this).find('a:contains("text which triggers append")').length > 0){
      $(this).siblings('td.quantity').append('<span>text to append</span>');
    }
  });
});
&#13;
td {
  border: 1px solid #000;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
        <td class="name"><a>text which triggers append</a></td>
        <td class="quantity">quantity</td>
    </tr>
    <tr>
        <td class="name"><a>other text</a></td>
        <td class="quantity">other quantity</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

正如您所提到的td.name&amp; td.quantity位于同一行,因此我使用jQuery siblings来获取td.quantity

希望这会对你有所帮助。