当我按回车键时,参考我所在的文本字段

时间:2015-09-30 03:37:20

标签: javascript jquery this keycode

Javascript / jQuery(没有按照我想要的方式工作):

function chkKey(event) {
    if (event.keyCode == 13) {
        $(this).val("value", "wow such code");
    };
};

我不想按名称引用文本字段,因为我在页面上有多个文本字段,这些字段使用相同的chkKey函数。我需要引用我目前所处的文本字段而不管名称。这可能吗?我认为这是一个父母/冒泡问题,但我根本没有这方面的经验。

编辑:完整的HTML / JS:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Boxes and Lines</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>

<body>
    <div id="outerDiv">
        <input type="button" name="btnNewField" value="Add New Field" onclick="appendNewField()">
        <p></p>
        <div id="mainDiv"></div>
    </div>

    <script>
        function chkKey(event) {
            if (event.keyCode == 13) {
                $(this).val("value", "wow");
            };
        };

        // returns a text field object
        function txtField(fieldName, fieldVal){
            var objTxtField = document.createElement("input");
            $(objTxtField).attr({
                type: "text",
                name: fieldName,
                value: fieldVal,
                onkeyup: "chkKey(event)"
            });
            return objTxtField;
        };

        // if there is no appended text field, create one and give it focus
        function appendNewField() {
            if ($("#mainDiv").find('[name="appTxtField"]').length === 0 ) {
                $(new txtField("appTxtField", "")).appendTo($("#mainDiv")).focus();
            };
        };
    </script>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

您的代码中有两个错误:

  • 使用val之类似attrprop,但它只需要一个参数
  • 尝试使用keyup添加attr事件处理程序,您应该使用on

请查看下面的代码,修改上述项目:

function chkKey(event) {
    if (event.keyCode == 13) {
        $(this).val("wow such code");
    };
};

// returns a text field object
function txtField(fieldName, fieldVal){
    var objTxtField = document.createElement("input");
    $(objTxtField).attr({
        type: "text",
        name: fieldName,
        value: fieldVal
    }).on('keyup', chkKey);
  
    return objTxtField;
};


// if there is no appended text field, create one and give it focus
function appendNewField() {
    if ($("#mainDiv").find('[name="appTxtField"]').length === 0 ) {
        $(new txtField("appTxtField", "")).appendTo($("#mainDiv")).focus();
    };
};

appendNewField()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mainDiv"></div>

答案 1 :(得分:1)

onkeyup: "chkKey(event, this)"会将当前元素传递给函数。