在div中添加div并设置值?

时间:2017-09-06 16:33:12

标签: javascript jquery html5 append

我需要填充多个表格。我使用jQuery循环遍历表格单元格。如果表格单元格具有data-text属性,则需要附加div元素。 Div元素将允许单元格具有垂直滚动条。如果文本太长,表格将不会消耗。

以下是我的代码示例:

$('#'+tabID+' table tr td').each(function(){
  elementID = $(this).prop('id').toUpperCase();
  value = $.trim(decodeURIComponent(obj.DATA[elementID]['value']));

  if($(this).attr('data-text')) {
    $(this).append('<div class="hm_textScroll">'+value+'</div>');
  } else {
    $(this).text(value).css({'color':'blue','font-weight':'bold'});
  }
});

上面的代码将附加div元素并设置值,但问题是如果我移动到另一个表并再次返回,则会追加一个div。这会造成重复。我不确定防止这种情况的最佳方法是什么?或者,如果有更好的方法来解决这个问题。如果有人有任何建议,请告诉我。

提前致谢。

2 个答案:

答案 0 :(得分:1)

您可以使用解决方案

tr

首先遍历每个td,然后循环遍历每个data-attribute

要查看typeof $(this).attr('data-text') != 'undefined,请使用ES6

在if语句中(真实条件)我使用反引号 public ActionResult soapReport(string path) { soapSSRS.ReportExecutionService rs = new soapSSRS.ReportExecutionService(); rs.Url = "http://xxx.xxx.xxx.xx:xxxx/reportserver/ReportExecution2005.asmx"; ; rs.Credentials = new System.Net.NetworkCredential( ConfigurationManager.AppSettings["ssrs_user"].ToString(), ConfigurationManager.AppSettings["ssrs_pass"].ToString(), ConfigurationManager.AppSettings["ssrs_domain"].ToString()); // Render arguments byte[] result = null; string reportPath = "/MyReportFolder/MyReport"; string format = "MHTML"; string historyID = null; string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; // Prepare report parameter. soapSSRS.ParameterValue[] parameters = new soapSSRS.ParameterValue[3]; parameters[0] = new soapSSRS.ParameterValue(); parameters[0].Name = "token"; parameters[0].Value = "XxXxXxXxXxXxXx"; DataSourceCredentials[] credentials = null; string showHideToggle = null; string encoding; string mimeType; string extension; soapSSRS.Warning[] warnings = null; ParameterValue[] reportHistoryParameters = null; string[] streamIDs = null; soapSSRS.ExecutionInfo execInfo = new soapSSRS.ExecutionInfo(); soapSSRS.ExecutionHeader execHeader = new soapSSRS.ExecutionHeader(); rs.ExecutionHeaderValue = execHeader; execInfo = rs.LoadReport(reportPath, historyID); rs.SetExecutionParameters(parameters, "en-us"); String SessionId = rs.ExecutionHeaderValue.ExecutionID; try { result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); execInfo = rs.GetExecutionInfo(); } catch (SoapException e) { Console.WriteLine(e.Detail.OuterXml); } } 来附加div容器。

希望这会对你有所帮助。

答案 1 :(得分:0)

如果我理解正确,您必须另外检查<div class="hm_textScroll"></div>中是否已存在<td>

使用vanilla javascript的一种可能的解决方案是:

const tableElement = document.querySelectorAll('#'+tabID+'table tr td');
tableElement.forEach(td => {
  if (td.hasAttribute("data-text")) {
    if (!td.querySelector(".hm_textScroll")) {
      td.innerHTML='<divclass="hm_textScroll">'+value+'</div>'
    }
  }
});