【问题标题】:Trying to insert an HTML Element into an another HTML Element using Javascript尝试使用 Javascript 将 HTML 元素插入另一个 HTML 元素
【发布时间】:2017-12-16 18:10:22
【问题描述】:

大家好,我正在尝试使用 Javascript 将 HTML 元素插入另一个 HTML 元素。

我尝试使用.insertAdjacentHTML,但由于位置不适合我,它会将其插入到目标元素附近...而.html 将其插入为文本格式而不是 HTML 格式

这是我尝试编码的内容:-

   SendClientMessage(COLORS_.white, "15px", "none", '<div class="ls-files">' + CMDS_List + '</div>');
   function SendClientMessage(color, font, align = 'none', message)
   {
      if(align !== "none")
      {
         output_.insertAdjacentHTML('beforeend', '<p style="color: ' + color + '; font-size: ' + font + '; text-align: ' + align + ';">' + message + '</p>'); 
      }
      else if(align === "none")
      {
         output_.insertAdjacentHTML('beforeend', '<p style="color: ' + color + '; font-size: ' + font + ';">' + message + '</p>'); 
      }
   }

输出:-

<p style="color: #FFFFFF; font-size: 15px;"></p>
<div class="ls-files">clear,clock,dati,ping,uname,whoami,cmd,</div>

【问题讨论】:

  • 预期输出是什么?
  • &lt;p style="color: #FFFFFF; font-size: 15px;"&gt;&lt;div class="ls-files"&gt;clear,clock,dati,ping,uname,whoami,cmd,&lt;/div&gt;&lt;/p&gt;
  • 你试过innerHTML或appendChild吗?
  • .insertAdjacentHTML("beforeend", ...) 的行为或多或少类似于.appendChild()。因此,仅当 output_ 不是 p 标记时才可能显示输出。
  • @brk 在尝试使用 appendChild 时遇到错误 Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. 所以我搜索了任何 smilliar 问题:stackoverflow.com/questions/27079598/… 但我无法使用这个插入任何样式表

标签: javascript jquery html format output


【解决方案1】:

您只能使用 insertAdjacentHTML 将 spana 等内联元素放入 p 标记中,因为它使用了一个 html 解析器来检查在插入内容之前正确格式化 html。

let CMDS_List = 'clear,clock,dati,ping,uname,whoami,cmd,';

SendClientMessage('white', "15px", "none", '<span class="ls-files">' + CMDS_List + '</span>');

function SendClientMessage(color, font, align = 'none', message) {
  let output_ = document.getElementById('output');
  if (align !== "none") {
    output_.insertAdjacentHTML('beforeend', '<p style="color: ' + color + '; font-size: ' + font + '; text-align: ' + align + ';">' + message + '</p>');
  } else if (align === "none") {
    output_.insertAdjacentHTML('beforeend', '<p style="color: ' + color + '; font-size: ' + font + ';">' + message + '</p>');
  }
}
  body {
  background: #999;
&lt;div id="output"&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 2010-10-23
    • 2014-10-10
    • 1970-01-01
    • 2014-01-21
    • 2014-07-22
    • 2022-07-06
    • 2017-06-14
    • 1970-01-01
    相关资源
    最近更新 更多