为分配给变量的名称属性键入事件处理程序

Key up event handler for name attribute assigned to a variable

我想为我页面上的每个文本字段创建一个 keyup 事件。我最终将有两个文本字段,它们都具有不同的名称属性。 (该示例只有一个文本字段。)每个文本字段都将通过按下我分配给它的按钮来创建。问题:

  1. 我可以为每个文本字段创建一个 keyup 事件吗?

  2. 如果我在创建文本字段之前调用 keyup 处理函数,keyup 函数会在新文本字段上触发吗?

  3. 我想在我的函数 txtField 中使用变量名来分配 keyup 处理程序。这将为文本字段创建一个 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();
    };
    

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

  1. 是的,你可以(我知道这听起来像是竞选口号)你应该阅读 direct-and-delegated-events
  2. 不,绑定事件到不存在的元素不会触发,除非您使用jquery的委托语法。再次 direct-and-delegated-events

  3. "txtField" 函数没有任何问题,您可以通过多种方式使用 jQuery 来实现它,但没有理由这样做 因为在如此简单的操作中 jQuery 抽象是不必要的。

"appendNewField" - 可以而且应该改进,原因如下:

  • $('[name="appTxtField"]') 每次调用函数时都要查找,这很糟糕。这实际上是在寻找节点并在每个 运行 上构建该节点的 jquery 实例("mainDiv" 也是如此)

我要做的是在 "appendNewField" 外部作用域中设置一个引用,并在每次调用时使用 jquery 的查找方法。例如:

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