2015-09-27 29 views
2

我想爲我的頁面上的每個文本字段創建一個鍵入事件。我最終會有兩個文本字段,都具有不同的名稱屬性。 (該示例只有一個文本字段。)每個文本字段都將通過按下分配給它的按鈕來創建。問題:鍵入分配給變量的名稱屬性的事件處理程序

  1. 我可以爲每個文本字段創建一個關鍵事件嗎?

  2. 如果我在創建文本字段之前調用keyup處理函數,那麼keyup函數會在新的文本字段上觸發嗎?

  3. 我想在我的函數txtField中使用變量名來分配keyup處理函數。這將爲名稱屬性與我的fieldName變量的值匹配的文本字段創建一個鍵盤事件處理程序。這可能嗎? $('[name = fieldName]')。keyup(myFunction)似乎不起作用。

  4. 有沒有更好的方法來做我想做的事情?

    // creates a text field 
    function txtField(fieldName, fieldVal){ 
        var objTxtField = document.createElement("input"); 
        objTxtField.type = "text"; 
        objTxtField.name = fieldName; 
        objTxtField.value = fieldVal; 
        return objTxtField; 
    }; 
    
    // button fires this function 
    // if there is no appended text field, create one and give it focus 
    function appendNewField() { 
        if ($('[name="appTxtField"]').length === 0) { 
         var newTxtField = new txtField("appTxtField", ""); 
         $("#mainDiv").append(newTxtField); 
        }; 
        $('[name="appTxtField"]').focus(); 
    }; 
    

回答

0
  1. 可以呀(聽起來像一個運動路線,我知道)你應該閱讀有關direct-and-delegated-events
  2. 沒有,事件綁定到不存在的元素將不火,除非你使用jQuery的代表團語法。再次direct-and-delegated-events

  3. 有沒有錯「txtField」功能,你可以在多種方式來實現這一目標已經使用jQuery的,但沒有理由這樣做 因爲jQuery的抽象是在這樣一個簡單的操作是不必要的。

「appendNewField」 - 可以而且應該得到改善,這裏的原因:

  • $( '[NAME = 「appTxtField」]')每函數被調用時擡頭一看,這是可怕。這實際上是在尋找構建該節點的jQuery的實例上的每個運行的節點&(同樣適用於「mainDiv」)

我會做的是設置在「appendNewField」外範圍的參考和使用每次調用jquery的find方法。例如:

var mainDiv = $("#mainDiv"); 

function txtField(fieldName, fieldVal) { ... }; 

function appendNewField() { 
    if (mainDiv.find('[name="appTxtField"]').length === 0) { 
     // utilize the chaining api and use focus directly after the appending. 
     $(new txtField("appTxtField", "")).appendTo(mainDiv).focus(); 
    }; 
} 
+0

你究竟在做什麼'.focus()'在你的例子中? –

+0

如果你想downvote,至少解釋爲什麼.. –

+0

我同意,人們會downvotes瘋狂... –

-1

var $mainDiv = $("#mainDiv"); 
 

 
// creates a text field 
 
function txtField(name, val){ 
 
    return $("<input />", { // Return a new input El 
 
    name: name,   // Assign Properties 
 
    value: val, 
 
    keyup: function(){ // And JS events 
 
     alert("key up! Yey"); 
 
    } 
 
    }); 
 
} 
 

 
// button fires this function 
 
// if there is no appended text field, create one and give it focus 
 
function appendNewField() { 
 
    if ($('[name="appTxtField"]').length === 0) { 
 
    var $newField = txtField("appTxtField", ""); // Create it 
 
    $mainDiv.append($newField);    // Append it 
 
    $newField.focus();       // Focus it 
 
    } 
 
} 
 

 
$("button").on("click", appendNewField);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button>Add field</button> 
 
<div id="mainDiv"></div>

或者,如果你更喜歡:

function appendNewField() { 
    if ($('[name="appTxtField"]').length > 0) return; // Exists already! Exit fn. 
    txtField("appTxtField", "").appendTo($mainDiv).focus(); 
} 

jsBin demo

相關問題