2015-09-27 28 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

相关问题