使用JavaScript为输入框添加onclick属性

22

我正在一个事件中创建用户输入:

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);
}

...但是生成的输入框没有onclick属性。我尝试使用

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

我尝试使用`...`代替,但是也没有起作用。我做错了什么?


1
你已经声明了所有变量吗?如果没有,那么你正在使用“隐含全局变量”,这不是很好——通过使用“var”关键字将它们声明为局部变量。 - Steve Harrison
4个回答

40

尝试这样做:

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

史蒂夫


尝试过了,但输入框没有获取到 onclick 属性。可能出了什么问题? - Alex
你是如何确定输入是否包含“onclick”函数的? - Steve Harrison
我打开FireBug并查看“HTML”部分是否存在。 - Alex
3
有趣。我尝试着创建一个带有“onclick”处理程序的元素并将其添加到DOM中,但它没有显示在HTML部分(但是onclick处理程序确实存在且有效)。尝试为输入添加ID属性(假设ID为“test”),并在Firebug控制台中执行以下代码(不包括单引号):'document.getElementById("test").onclick'。你会收到一个函数吗? - Steve Harrison

6

您的代码中有一行存在问题,我已经为您进行了修正:

 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);
 }

这样更容易理解吗?

2

如果您想传递这些字符,我认为您需要转义 \r\n。

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

我不太明白您的onclick处理程序试图实现什么...


啊,这没问题,它很好地工作了(它通过TCP套接字发送一行)。我实际上卡在了将onclick属性附加到输入标记上。 - Alex

1
这是我决定使用jQuery的原因之一:
 $('<input type="submit" value="Join chat" />')
      .click( function() { conn.send('$connect\r\n'); } )
      .appendTo('<div></div>')
      .appendTo('#box');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接