2017-03-09 4 views
0

ボタンからonclickイベントを発生させたいと思います。イベントは別のJavaScriptファイルで宣言されます。JavaScriptイベントボタンonclickは1回だけ動作します

コードはチャットを再現する必要があります。私は最初のテキストを送信する場合、それは正常に動作しますが、私は何かをもう一度(2番目のテキスト)を送信しようとすると起動しません。

HTMLファイルが含まれています

var chatOutputDiv = document.getElementById("chatOutput"); 
 
chatSubmit.onclick = function() { 
 
     // Create a Json object with "displayname" being the display name and "messageText" the message. 
 
     // "displayname" is taken from URL, message from element chatInput. 
 
     //var chatMessage = { "displayname": getURLParameter("displayName"), "messageText": chatInput.value }; 
 
     // We send data on the "chat", channel which is currently hard-coded 
 
     // in later versions we allow custom naming of channels. 
 
     //conference.sendData("chat", chatMessage); 
 
     // Send text in current chat 
 
     chatOutputDiv.innerHTML += "<br> user : message"; 
 
     // Clear chat input 
 
     chatInput.value = ""; 
 
    };
<div class="row"> 
 
    <div class="col-xs-12 col-lg-12 col-sm-12 col-md-12" align="center"> 
 
     <div id="chatOutput" style="height: 200px; width: 220px; overflow-y: scroll;"> 
 
      <input type="text" id="chatInput"/> 
 
      <input id="chatSubmit" type="button" value="Send"/> 
 
     </div> 
 
    </div> 
 
</div>

あなたはこのコードをしようとすると、それは1時間に動作しますが、その後、それはもう動作しません。それはイベントを発生させないようだ。

答えて

2

ボタンをクリックするとHTMLが.chatOutput内に再作成され、HTML(ボタンを含む)が書き換えられてイベントが失われるためです。

これにはさまざまな方法があります。 1つは、関数を呼び出す名前付き関数にし、関数の最後にchatSubmit = document.getElementById("chatSubmit"); chatSubmit.onclick = myFunctionName;を追加することです。

しかし、私はそうのように、それを行うためのよりよい方法はちょうど応答を保存するために、余分なdiv要素を使用することであると思う:

<div class="row"> 
<div class="col-xs-12 col-lg-12 col-sm-12 col-md-12" align="center"> 
    <div id="chatOutput" style="height: 200px; width: 220px; overflow-y: scroll;"> 
     <input type="text" id="chatInput"/> 
     <input id="chatSubmit" type="button" value="Send"/> 
     <div id="chatResponse"></div> 
    </div> 
</div> 
</div> 


var chatOutputDiv = document.getElementById("chatOutput") 
var chatSubmit = document.getElementById("chatSubmit") 
var chatResponse = document.getElementById("chatResponse"); 
var chatInput = document.getElementById("chatInput"); 

function foobar() { 
    chatResponse.innerHTML += "<br> user : " + chatInput.value; 
    chatInput.value = ""; 
} 

chatSubmit.onclick = foobar; 

フィドル:https://jsfiddle.net/r0gm30mr/

関連する問題