jQuery each函数:未按预期正确获取数据

jQuery each function: not properly getting data as expected

本文关键字:获取 数据 each 函数 jQuery      更新时间:2023-09-26

由于某些原因,我无法从下面指定的第二个TD获得text/html

模板标签是Django。

{% block content %}
{% if host.host_scripts %}
<table class="table">
  <button class="btn btn-info add" id="{{forloop.counter}}">Add to session</button>
  {% for script in host.host_scripts %}
     <tr>
        <td id="script-name-{{forloop.counter}}">{{script.scriptName}}</td>
        <td id="script-output-{{forloop.counter}}">{{script.scriptOutput|linebreaks}}</td>
     </tr>
  {% endfor %}
</table>
{% endif %}
<script>
$(".add").click(function(e) {
   var id = $(this).attr('id');
   scriptList = []
   e.preventDefault();
   $("#myTable-"+id+" tr ").each(function() {
       var name = $(this).find('#script-name-'+id).html();
       var output = $(this).find('#script-output-'+id).html();
       var myList = [name, output];
       console.log('Name -> ' + name);
       console.log('Output -> ' + output);
       scriptList.push(myList);
   });
});
</script>
{% endblock %}

我可以很好地获得名称变量。由于某些原因,我无法获取scriptOutput变量。

我认为这是由于|linebreaks ,但删除它对行为没有影响。

期望行为:

根据表中的tr,获取td的内容并添加到列表中。

当前行为:

它只获取了name变量,出于某种原因跳过了scriptOutput变量。

我设法获得了"some"输出,现在我为每个scriptName的输出返回了相同的值。我很困惑,因为我看不出身份证出了什么问题。

{% block content %}
{% if host.host_scripts %}
<table class="table myTable">
  <button class="btn btn-info add" id="{{forloop.counter}}">Add to session</button>
  {% for script in host.host_scripts %}
     <tr>
        <td id="script-name-{{forloop.counter}}">{{script.scriptName}}</td>
        <td id="script-output-{{forloop.counter}}">{{script.scriptOutput|linebreaks}}</td>
     </tr>
  {% endfor %}
</table>
{% endif %}
<script>
var scriptList = []
$("#myTable-"+id+" tr").each(function() {
    var name = $(this).find('td:first').html();
    var output = $('#script_output-'+id).html();
    var script = [name, output];
    scriptList.push(script);
    console.log('Text: ' + output);
});
console.log(scriptList);
</script>

我知道我可能应该将我的ID扩展到某种类型:

<td id="script-output-{{forloop.parentloop.counter}}-{{forloop.counter}}">{{script.scriptOutput|linebreaks}}</td>

然而我似乎不明白,我做错了什么??

试试这个:

<script>
$(".add").click(function(e) {
   var id = $(this).attr('id');
   scriptList = []
   e.preventDefault();
   $("#myTable-"+id+" tr ").each(function(index, el) {
       var name = $(el).find('#script-name-'+id).html();
       var output = $(el).find('#script-output-'+id).html();
       var myList = [name, output];
       console.log('Name -> ' + name);
       console.log('Output -> ' + output);
       scriptList.push(myList);
   });
});
</script>