Add onclick property to input with JavaScript

2019-01-25 04:43发布

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?

4条回答
对你真心纯属浪费
2楼-- · 2019-01-25 05:01

Try this:

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

Steve

查看更多
Lonely孤独者°
3楼-- · 2019-01-25 05:07

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楼-- · 2019-01-25 05:14

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?

查看更多
爷的心禁止访问
5楼-- · 2019-01-25 05:16

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');
查看更多
登录 后发表回答