2014-08-29 28 views
2

我有這樣的腳本:的Javascript追加投入,形成

var countBox = 0; 

function addInput() { 
var breakNode = document.createElement("br"); 

var input = document.createElement("input"); 
input.type = "text"; 
input.name = "input_" + countBox.toString(); 
input.placeholder = "Notes"; 
input.onkeydown = "tab()"; 

var container = document.getElementById('container'); 
container.appendChild(breakNode); 
container.appendChild(input); 

countBox += 1; 
} 

它應該返回

<input type="text" name="input_0" placeholder="Notes" onkeydown="tab()"> 

但它只返回

<input type="text" name="input_0" placeholder="Notes"> 

但input.onkeydown不起作用有沒有辦法創建第一個元素,最好用Javascript,所以我可以動態創建一個新的字段,當用戶按下輸入?

+3

該事件需要一個函數,而不是一個字符串。 – elclanrs 2014-08-29 06:10:06

+2

elclanrs所說的+由屬性設置的事件處理程序不反映屬性。 – Teemu 2014-08-29 06:12:09

+0

@elclanrs函數的目的是創建一個輸入元素,其屬性類型爲「text」name =「input_0」palceholder =「Notes」onkeydown =「tab()」,但是當我告訴它添加onkeydown屬性時,它不會'註冊,所以我如何添加此? – Jdoonan 2014-08-29 06:13:42

回答

2

你想要的是input.onkeydown = tab;

這是一個fiddle,它顯示它正在運行。

在Javascript,Python和許多其他腳本語言中,函數可以作爲參數或參數傳遞。在這裏,我們將功能tab()作爲onkeydown屬性的值。

+0

不幸的是,當我運行該腳本的整個輸入消失。 – Jdoonan 2014-08-29 06:18:46

+0

不要從小提琴中複製整個東西 - 只是代碼行,'input.onkeydown = tab;'。我需要整個代碼來展示它的工作原理。 – Singular1ty 2014-08-29 06:19:35

+1

問題是如果tab的功能沒有被創建,那麼該功能失敗,並且該元素沒有被創建 – Jdoonan 2014-08-29 06:23:54