代码之家  ›  专栏  ›  技术社区  ›  Sailing Judo

如何使用jquery访问输入字段文本?

  •  0
  • Sailing Judo  · 技术社区  · 15 年前

    我正在尝试使用jquery的typewatch插件。我有这个javascript:

     <script type="text/javascript">
     $(document).ready(function() {
       var options = {
            callback: function() { alert("a-ok!  " + $(this).text); },
            wait: 333,
            highlight: true,
            captureLength: 1
        }
    
        $("#customer").typeWatch(options);
     });
     </script>
    

    我的视图的HTML有:

     Method B: <%= Html.TextBox("customer") %>
    

    在这个测试中,如果我在文本框中键入“abc”,我希望会弹出一个带有“a-ok!”的警报。ABC“。相反,会出现以下内容…

    a-ok!  function (F) {
        if (typeof F !== "object" && F != null) {
            return this.empty().append((this[0] && this[0].ownerDocument || 
                   document).createTextNode(F));
        }
        var E = "";
        o.each(F || this, function () {o.each(this.childNodes, function () {
              if (this.nodeType != 8) {
                 E += this.nodeType != 1 ? this.nodeValue : o.fn.text([this]);}});});
       return E;
    }
    

    我尝试将$(this).text更改为.val,并尝试更直接地将输入字段引用为$(“客户”),但结果类似。如何仅访问输入的文本?

    2 回复  |  直到 11 年前
        1
  •  1
  •   Lucas    15 年前

    在查看2.0版的TypeWatch代码时,我发现:

        function checkElement(timer, override) {
            var elTxt = jQuery(timer.el).val(); <----------- !!! this...
    
            // Fire if text > options.captureLength AND text != saved txt OR if override AND text > options.captureLength
            if ((elTxt.length > options.captureLength && elTxt.toUpperCase() != timer.text) 
            || (override && elTxt.length > options.captureLength)) {
                timer.text = elTxt.toUpperCase();
                timer.cb(elTxt); <-------------- !!! ...goes here.
            }
        };
    

    timer.cb是在选项中设置的回调。所以您只需在使用的回调函数中添加一个参数,该参数就是输入的文本。

        2
  •  5
  •   Ropstah    15 年前

    您应该在文本框上使用val()函数:

    $(this).val();