【问题标题】:$("user-input").is(":focus") , ("*:focus") , ("input:focus") are not working [closed]$("user-input").is(":focus") , ("*:focus") , ("input:focus") 不工作 [关闭]
【发布时间】:2020-04-05 19:17:07
【问题描述】:

我看到很多关于“:焦点”的问题,但没有看到很多有用的答案,包括基于文本的游戏的上下文或在 if 语句中使用。我想确定我写的内容是正确的,我的代码没有任何错误,我只是没有得到回报。我非常想为这个游戏编写代码,但遗憾的是直到我通过这个驼峰才能开始!提前感谢您的帮助!

我也发现了这个问题,https://https://stackoverflow.com/questions/967096/using-jquery-to-test-if-an-input-has-focus?rq=1。 它问了,看起来我遵循了答案,但错误代码仍然指向该代码行中的某些内容。

这是我的 HTML 文档,但我几乎可以肯定这里没有任何问题。

        <!DOCTYPE HTML>
        <head>
           <title>Zork!!</title>
        </head>
       <body>
       <div id = "game text"><p>Welcome to Zork!!</div>
       <input id = "user-input" placeholder="Please type your command.."></input>

       <script type="text/javascript" src="jquery-3.4.1.min.js"></script>

       <script type="text/javascript" src="script.js"></script>
       </body>

这是我在更改答案之前的原始“script.js”:

         $(document).ready(function(){
         $(document).keypress(function(key){


        if(key.which === 13 && $("user-input").is("*:focus")){
            //I also used "input: focus" and got the same error code
            var value = $("user-input").val();

            alert(value);
             }
           })   
         })

凭借我所拥有的,我认为我可以在输入框中输入单词并按回车键,然后在一个文本框中回复我输入的任何内容。

错误代码:

jquery-3.4.1.min.js:2 Uncaught Error: Syntax error, unrecognized expression: 
: focus
at Function.se.error (jquery-3.4.1.min.js:2)
at se.tokenize (jquery-3.4.1.min.js:2)
at se.compile (jquery-3.4.1.min.js:2)
at se.select (jquery-3.4.1.min.js:2)
at se (jquery-3.4.1.min.js:2)
at Function.se.matchesSelector (jquery-3.4.1.min.js:2)
at Function.k.filter (jquery-3.4.1.min.js:2)
at j (jquery-3.4.1.min.js:2)
at k.fn.init.is (jquery-3.4.1.min.js:2)
at HTMLDocument.<anonymous> (script.js:7)
//This is the line pointing to the :focus issue I was having

谢谢阿米特和易卜拉欣!

【问题讨论】:

  • 您的&lt;input&gt; 的id 属性值“用户输入”无效,带有空格。 jQuery 代码查找"user-input"
  • @Pointy 我像你说的那样把它改回“用户输入”,然后去掉了标签。你知道像我这样使用焦点有什么问题吗?每当我取出那部分代码时,HTML 工作正常,每当我按 Enter 键时,它都会返回“未定义”,因为没有任何焦点吸引到应该返回的内容。
  • 不不,你误会了。元素的 id 必须是“用户输入”。 id 属性值中不允许有空格。
  • 另外,你的 jQuery 选择器应该是 "*:focus""input:focus"
  • @Pointy 感谢您对第一部分的澄清!我尝试了您的两个焦点选择器,但仍然收到相同的错误代码。我应该把它们像 .is("*focus") 吗?

标签: javascript jquery text-based


【解决方案1】:
  1. 在您的 script.js 文件中使用此代码。

    $("#user-input").keypress(function(key){
        if(key.which === 13 && $('#user-input').is(':focus')){
            var value = $('#user-input').val();
            alert(value);
        }
    }) ;
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-27
    • 2021-12-04
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多