开发者

javascript write a line of html code with a button

hey guys i have got this far with a chat system but now i am stuck at this point.

the js script will look for a element called chat and if it is not found it will put it in with all of the other elements stated here

<div class='chat' id='chat'><div class='ch' id='ch'><h2>Chat</h2></div><div class='chatbox'><div class='messages'></div><textarea id='message' class='chatinp' rows='3' cols='27'></textarea><button class='send'>Send</button></div></div>

My problem is how to insert that whole line of code with javascript into the html document. how wou开发者_JS百科ld you do this?

My javascript script is you need to see

<script type="text/javascript">
var num = new Number();
num = 0

function chat(){


if(!document.getElementById("chat")){
       document.write("<div class='chat' id='chat'><div class='ch' id='ch'><h2>Chat</h2></div><div class='chatbox'><div class='messages'></div><textarea id='message' class='chatinp' rows='3' cols='27'></textarea><button class='send'>Send</button></div></div>")   
} 
else 
{
var obj = document.getElementById("chat").cloneNode(true);
var p = $(".chat");
var offset = p.offset();
num = num + 1;        

if (num <15) {
obj.id = obj.id + num;
document.getElementById("ch").id = obj.id;
document.body.appendChild(obj);
document.getElementById("chat").style.left = "700px";
}
}




}
</script>


Don't use document.write (it will overwrite everything in your document), but create div#chat dynamically, something like:

if(!document.getElementById("chat")){
  var chatdiv = document.createElement('div');
  chatdiv.id = 'chat';
  chatdiv.className = 'chat';
  chatdiv.innerHTML = 
              ['<div class="ch" id="ch">',
               '<h2>Chat</h2></div>',
               '<div class="chatbox">',
               '<div class="messages"></div>',
               '<textarea id="message" class="chatinp" ',
               'rows="3" cols="27"></textarea>',
               '<button class="send">Send</button></div>'
              ].join(' ')
  document.body.appendChild(chatdiv);
}

[Edit 2022] A more modern approach may be:

document.querySelector(`#chat`) || (_ => 
  document.body.insertAdjacentHTML(
    `beforeend`, `
    <div id="chat">
      <div class="ch" id="ch"> 
        <h2>Chat</h2>
      </div> 
      <div class="chatbox"> 
        <div class="messages"></div> 
        <textarea id="message" class="chatinp" rows="3" cols="27"></textarea> 
        <br><button class="send">Send</button>
      </div>
    </div>`)
)();

document.querySelector(`#chat #message`).placeholder = `Type something!`;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜