2015-08-26 40 views
1

我正在嘗試創建可在所有html頁面中使用的庫代碼。 我對JS非常陌生,這是我試圖像庫函數一樣編寫的第一個代碼。在外部文件中未觸發的單擊事件

我有一個文本字段,旁邊有一個按鈕,在按鈕的點擊,這增加旁邊低於另一個文本字段和一個按鈕,這也將刪除上一行的按鈕。

我設法在同一行做一個按鈕,並在下一行添加文本字段,但新添加的方法的按鈕點擊不適用於純JS,所以我嘗試使用jquery「on」點擊事件。由於某種原因,它不會在我的情況下觸發。 不知道我錯過了什麼。

代碼在外部文件

var addAnother = { 
    addAnotherField: function (eventTrigger, fieldContainer, arrayField) { 
     console.log("called"); 
     var eventTrigger = eventTrigger; 
     console.log("ready called", eventTrigger); 
     $(document).on('click', eventTrigger, function (e) { 
      console.log("click called"); 
      var buttonText = this.value; 
      var div = document.getElementById(fieldContainer); 
      var element = document.getElementById(eventTrigger); 
      element.parentNode.removeChild(element); 
      var input = document.createElement("input"); 
      input.type = "text"; 
      input.name = arrayField; 
      div.appendChild(document.createElement("br")); 
      div.appendChild(input); 
      var button = document.createElement("input"); 
      button.type = "button"; 
      button.id = eventTrigger; 
      button.value = buttonText; 
      div.appendChild(button); 
     }); 
    } 
} 

在HTML代碼

$(document).ready(function() { 
    addAnother.addAnotherField("addAnother", "addAnotherContainer", "fieldArray[]"); 
}); 

工作JS代碼: http://jsfiddle.net/balasivagnanam/ekoob8f0/

下一個按鈕不工作的代碼JS http://jsfiddle.net/balasivagnanam/ukseeuak/

使用jQuery: http://jsfiddle.net/balasivagnanam/6ea2dk6m/

回答

1

這是你想要的東西:

/** this part will be located in another file added as a js library */ 
function addAnother(elem) { 
    var text = $("#addAnotherField").clone(); 
    $("<br/>").insertBefore($("#addAnother")); 
    text.insertBefore($("#addAnother")); 

} 
/* this part will be coded below the above code file in the html file*/ 

$(document).ready(function() { 
    $('#addAnother').click(function() { 
     addAnother(this); 
    }); 
}); 

Here is the JSFiddle demo

+1

非常感謝+1 –