Add onclick property to input with JavaScript

2019-01-25 04:15发布

问题:

I am creating a user input at one of the events:

var throwConnectBox = function() {
    chat_box = document.getElementById('box');
    div = window.parent.document.createElement('div');
    input = window.parent.document.createElement('input');
    input.type = "submit";
    input.value = "Join chat";
    input.onclick = "conn.send('$connect\r\n');";
    div.appendChild(input);
    chat_box.appendChild(div);
}

... but the resulting input does not have onclick property. I tried to use

    input.onclick = conn.send('$connect\r\n');

... instead, but didn' work either. What am I doing wrong?

回答1:

Try this:

 input.onclick = function() { conn.send('$connect\r\n'); };

Steve



回答2:

There is a problem with one of your lines here; I've corrected it for you:

 var throwConnectBox = function() {
     chat_box = document.getElementById('box');
     div = window.parent.document.createElement('div');
     input = window.parent.document.createElement('input');
     input.type = "submit";
     input.value = "Join chat";
     /* this line is incorrect, surely you don't want to create a string? */
     // input.onclick = "conn.send('$connect\r\n');";?
     input.onclick = function() { 
         conn.send('$connect\r\n'); 
     };
     div.appendChild(input);
     chat_box.appendChild(div);
 }

Does that make more sense?



回答3:

I think you may want to escape the \r\n, if you intend to pass these...

conn.send('$connect\\r\\n')

I don't quite see what your onclick handler tries to achieve...



回答4:

This is one of the reasons why I've decided to use jQuery:

 $('<input type="submit" value="Join chat" />')
      .click( function() { conn.send('$connect\r\n'); } )
      .appendTo('<div></div>')
      .appendTo('#box');