在 insertAdjacentHTML 之前声明一个空元素

Declaring an empty element before insertAdjacentHTML

你好我有一个简单的问题,我需要在下面的函数before insertAdjacentHTML中指定lblWelcomeUserMessage.innerHTML = ""; ( see below in code )吗?它实际上没有声明就按原样工作,但我想知道什么是 optimal approach ?

// Dynamic HTML / user interface for ALL users
  function showWelcomeMessage() {

      //lblWelcomeUserMessage.innerHTML = "";

      var sWelcomeUserMessage = '<h3>' + 'Welcome:' + '  ' + sessionStorage.getItem( 'name' ) + 
      '  ' +  sessionStorage.getItem( 'lastname' ) + '  ' + sessionStorage.getItem( 'role' ) + ' </h3>';
      var iUserImage = '<img src=" ' + sessionStorage.getItem( 'image' ) + ' " width="50px">';
      lblWelcomeUserMessage.insertAdjacentHTML( 'beforeend', sWelcomeUserMessage + iUserImage );
  }

insertAdjacentHTML inserts some HTML around a nodelblWelcomeUserMessage,你应该在 lblWelcomeUserMessage = document.getElementById('welcome_tag') 之前得到它)。

将它的内部内容设置为空字符串并不是真正必要的,除非你想清除它。这与其说是程序问题,不如说是设计问题。

什么是最佳方法?

顺便说一下基于 MDN:

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

insertAdjacentHTML() parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position. It does not reparse the element it is being used on and thus it does not corrupt the existing elements inside that element. This avoids the extra step of serialization, making it much faster than direct innerHTML manipulation.

所以这基本上取决于您的需求。如果你想替换以前的消息,你只需添加 lblWelcomeUserMessage.innerHTML = ""; ,如果你想显示所有以前的消息,只需注释该代码。

这取决于你想做什么。

If you are calling showWelcomeMessage function more than once then you need to set it to empty lblWelcomeUserMessage.innerHTML = ""

       function showWelcomeMessage() {

  lblWelcomeUserMessage.innerHTML = "";

   var sWelcomeUserMessage = '<h3>' + 'Welcome:' + '  ' + sessionStorage.getItem( 'name' ) + 
  '  ' +  sessionStorage.getItem( 'lastname' ) + '  ' + sessionStorage.getItem( 'role' ) + ' </h3>';
  var iUserImage = '<img src=" ' + sessionStorage.getItem( 'image' ) + ' " width="50px">';
  lblWelcomeUserMessage.insertAdjacentHTML( 'beforeend', sWelcomeUserMessage + iUserImage );
  }

   setInterval(showWelcomeMessage,4000);

Otherwise you can remove lblWelcomeUserMessage.innerHTML = ""; from above code