【问题标题】:How to make text box enable and disable in jquery [duplicate]如何在jquery中启用和禁用文本框[重复]
【发布时间】:2014-01-06 15:17:32
【问题描述】:

我写了一个html和脚本的示例代码如下: 当我首先执行此代码时,我会收到该警报 hello,但当我通过按 tab 按钮在 cca 更改时会收到其他警报,然后它不会显示警报。如何使用该文本框并启用和禁用它的其他文本字段。

HTML:

<div id="cca" class="leaf">
     <label class="control input text" title="">
        <span class="wrap">cca</span>
        <input class="" type="text" value="[Null]">
        <span class="warning"></span>
     </label>
</div>

JS:

jQuery(document).ready(function () {        
    alert("hello");        
    jQuery("#cca label.control input").on('change', function (event) {
        alert('I am pretty sure the text box changed');
        event.preventDefault();
    });
});

【问题讨论】:

  • 首先你的 html 坏了。您可以在标签内使用那么多元素,这不是很好。而且您的标签没有达到目的,您没有使用for 属性。

标签: javascript jquery html


【解决方案1】:

我不太确定您要做什么,但我可以帮助让警报正常工作。您基本上没有正确使用 jQuery "on" 功能。

$('#thisNeedsToBeContainer').on('focusout', '#elemToBindEventTo', function (event)....

以下其中一项将满足您的需要:

离开文本框时会触发

$(document).ready(function () {      

    alert("hello");        
    $("#cca").on('focusout', 'label.control input', function (event) {
        alert('I am pretty sure the text box changed');
        event.preventDefault();
    });
});

这将在change 上触发

$(document).ready(function () {       
    alert("hello");        
    $("#cca").on('change', 'label.control input', function (event) {
        alert('I am pretty sure the text box changed');
        event.preventDefault();
    });
});

这会在输入时触发keyup

$(document).ready(function () {  
    alert("hello");        
    $("#cca").on('onkeyup', 'label.control input', function (event) {
        alert('I am pretty sure the text box changed');
        event.preventDefault();
    });
});

在JsFiddle上查看演示

您还应该关闭您的输入:

<input class="" type="text" value="[Null]"/>

【讨论】:

  • 我可以像使用focusout一样使用按键和更改吗
  • 感谢 Jon 提供您与我共享的代码,但事情是在我的浏览器中执行它并没有接受任何“on”事件,所以我不能使用该代码.....它会引发错误,例如“未捕获的 TypeError:无法调用 null flow.html 的“on”方法?_flowId=viewReportFlow&standAlone=true&_flowId=viewReportFlow&ParentFolderUri=%2Freports%…:1035(匿名函数)flow.html?_flowId=viewReportFlow&standAlone=true&_flowId=viewReportFlow&ParentFolderUri= %2Freports%…:1035 n jquery-1.7.1.min.js:2 o.fireWith jquery-1.7.1.min.js:2 e.extend.ready jquery-1.7.1.min.js:2 c。 addEventListener.B"
  • 我唯一改变的是jQuery到$。不确定您如何没有冲突设置。不过应该在 1.7.1 中工作。也许试试... jQuery(document).ready(function () { alert("hello"); jQuery("#cca").on('focusout', 'label.control input', function (event) { alert ('我很确定文本框已更改'); event.preventDefault(); }); });
【解决方案2】:

您正在侦听change 事件,该事件在输入失去焦点之前不会触发。鉴于一旦焦点离开输入(通过选项卡或单击),您提供的代码确实会触发警报,我猜您在输入后但在更改焦点之前期望得到响应。为此,请改为监听 input 事件。

【讨论】:

    猜你喜欢
    • 2014-01-06
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 2017-07-30
    相关资源
    最近更新 更多