代码之家  ›  专栏  ›  技术社区  ›  brad90

使用jquery禁用焦点字段

  •  -2
  • brad90  · 技术社区  · 8 年前

    我尝试创建一个jquery代码,该代码执行以下操作:

    如果我将id为“ac\u inp”的字段设置为焦点,则id为“ac\u sel”的选择字段将被禁用。如果我选择id为“ac\u sel”的选择字段,id为“ac\u inp”的字段将被禁用。但它不起作用。怎么了?

    $(document).ready(function () {
        if ($("#ac_inp").is(':focus')) {
            $("#ac_inp").prop('disabled', false)
            $("#ac_sel").prop('disabled', true)
        }
        if ($("#ac_sel").is(':focus')) {
            $("#ac_inp").prop('disabled', true)
            $("#ac_sel").prop('disabled', false)
        }
    });
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Luca Mazzanti    8 年前

    在代码段中,您准备了一个脚本,该脚本在文档加载时运行一次。

    在这种情况下,您需要为焦点创建事件,而不是一个不再运行的检查。

    <script>
    $(document).ready(function () {
    
      $("#ac_inp").focus(function() {
         $(this).prop('disabled', false);
         $("#ac_sel").prop('disabled', true);
      });
    
      $("#ac_sel").focus(function() {
        $(this).prop('disabled', false);
        $("#ac_inp").prop('disabled', true);
      });
    
    });
    </script>