【问题标题】:Add onclick property to input with JavaScript添加 onclick 属性以使用 JavaScript 进行输入
【发布时间】:2010-10-21 20:21:50
【问题描述】:

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

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

... 相反,但也没有工作。我做错了什么?

【问题讨论】:

  • 您是否已经声明了所有这些变量?如果不是,那么您使用的“隐含全局变量”不是很好——通过使用“var”关键字声明它们来使它们成为局部变量。

标签: javascript input onclick


【解决方案1】:

这是我决定使用 jQuery 的原因之一:

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

【讨论】:

    【解决方案2】:

    您的其中一条线有问题;我已经为你更正了:

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

    这样更有意义吗?

    【讨论】:

      【解决方案3】:

      如果你打算通过这些,我认为你可能想逃避 \r\n...

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

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

      【讨论】:

      • 啊,没问题,它工作正常(它通过 TCP 套接字发送一条线路)。我实际上坚持将 onclick 属性附加到输入标签。
      【解决方案4】:

      试试这个:

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

      史蒂夫

      【讨论】:

      • 试过了,但是输入没有得到onclick属性。那里可能会发生什么?
      • 你如何确定输入是否有“onclick”功能?
      • 我去 FireBug 看看“HTML”部分是否有。
      • 有趣。我很快尝试使用“onclick”处理程序创建一个元素并将其添加到 DOM,但它没有显示在 HTML 部分中(但 onclick 处理程序在那里并且正在工作)。尝试向输入添加 ID 属性(假设 ID 为“test”),并在 Firebug 的控制台中执行以下代码(不带单引号):'document.getElementById("test").onclick'。你找回一个函数吗?
      猜你喜欢
      • 2011-04-17
      • 1970-01-01
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 2013-04-02
      • 2012-03-16
      • 2017-01-09
      相关资源
      最近更新 更多