使用JQuery动态增加td-id

使用JQuery动态增加td-id,jquery,ruby-on-rails,Jquery,Ruby On Rails,如何使用jQuery在下面的代码中以串行顺序为td id=所选的_设备提供动态id值 我需要附加每个设备的状态是在线或离线。我正在为每个td获取不同的状态值,但它被覆盖,因为它具有相同的id。我已包含我的ajax调用。它将采用mac长度,检查mac是否在线,并将结果附加到相应的列中。当前代码仅覆盖每个td单元中的最后一个状态。因为所有设备的td id都相同 <td class="Selected_Device" id="Selected_Device"> HTML JS文件

如何使用jQuery在下面的代码中以串行顺序为td id=所选的_设备提供动态id值

我需要附加每个设备的状态是在线或离线。我正在为每个td获取不同的状态值,但它被覆盖,因为它具有相同的id。我已包含我的ajax调用。它将采用mac长度,检查mac是否在线,并将结果附加到相应的列中。当前代码仅覆盖每个td单元中的最后一个状态。因为所有设备的td id都相同

    <td class="Selected_Device" id="Selected_Device">
HTML

JS文件

function getDeviceType() {

   var selected_Device_Mac ;

 var selected_device_id = '';

         if ($('#PA').is(":visible")) {
         console.log("before")
         selected_Device_Mac = document.querySelectorAll(".macAddr");
         var k=selected_Device_Mac.length;
          selected_device_id = document.querySelectorAll(".Selected_Device");

  for (var i=0;i<k;i++){
 $.ajax({

         method: "GET",
         dataType: "text",
         url: "getDeviceStatus",
         data: {
             mac : selected_Device_Mac[i].innerText,
         },

         success: function(result) {
             if(result!==""){

                 if(result.includes("On-line")){
                    //$(selected_device_id).html("");
                    $(selected_device_id).append(result+"&nbsp;&nbsp;&#9989;");

                 }else if(result.includes("Off-line")){
                    // $(selected_device_id).html("");
                     $(selected_device_id).append(result+"&nbsp;&nbsp;&#10071;");


                 }


             }
        }

     }

 );

}

我会这样做:

#in your view 
<td class="Selected_Device" id="Selected_Device_<%= parameter.id %>">

#in your js.erb
selected_device_id = document.getElementById("#Selected_Device_<%= parameter.id %>");

我将按照以下方式完全重写您的js代码:

函数getDeviceType{ 如果!$'PA'。是否可见{ 回来 } $.macAddr.eachfunctionindex,macAddrEl{ $.ajax{ 方法:获取, 数据类型:文本, url:getDeviceStatus, 数据:{ mac:$macAddrEl.text.trim, }, 成功:结果{ 如果结果为!=={ var nextColumnCell=$macAddrEl.parenttr.find.Selected\u设备 如果结果包括在线{ nextColumnCell.appendresult+&9989; }否则,如果结果。包括脱机{ nextColumnCell.appendresult+&10071;; } } } } 它获取类为macAddr BTW的元素列表。在模板中,您有macaddress类,对于每个元素,它获取其内容$macAddrEl.text.trim,然后它搜索类为Selected_Device的元素,该设备与当前mac元素$macAddrEl.parenttr.find.Selected_Device具有相同的父tr

您可以看到省略的ajax部分,它只读取带有MacAddress类的单元格内容,并使用带有索引的选定类填充单元格

由于id必须是唯一的,所以您必须

<td class="Selected_Device" id="Selected_Device_<%= parameter.id %>">

或者,如果您不使用它,您可以删除id。

您应该正确缩进和格式化代码,这会使阅读更容易,帮助您快速阅读。如果您可以解释更多问题,并提供一些您希望得到的原始数据示例,则会更好。添加Js代码也谢谢。但它仍然覆盖所有td单元的相同值。我更新了我们的答案e getElementById而不是QuerySelectorAllThank。现在td id值与预期值相同。但它再次覆盖了值。我需要在此处进行更改吗?$selected_device_id.appendresult+&9989;;在哪里设置结果?谢谢。我需要在index和MacAddressel中传递什么值。如果不传递任何值,jQuery会为您传递-$。macAddr返回具有给定类的元素数组,为每个元素调用回调,所以index是当前元素的索引,macAddrEl是当前元素。您可以分叉codepen演示并使用它来查看它是如何工作的
<td class="Selected_Device" id="Selected_Device_<%= parameter.id %>">