我尝试按如下方式编写“如果用户未选择ID为'id-1'的表单”,但这就像传递了if语句一样工作。有什么事吗



    $(document).on("keyup",
      function(p_k) {
        var target = $(this);
        if (target.is("id-1")) {} else {
          //do this ...
        }
      }
    );

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1>Chat#index</h1>

<ul id="chat_area">
</ul>
<input id="id-1" class='form-control' type="text">

最佳答案

首先,您尝试将事件处理程序添加到文档中(它本身不会触发“ keyup”事件。

其次,检查ID的语法已关闭。

观看演示:



$("input").on("keyup",
  function(event)
  {
    var target = $(this);

    if (target.attr("id") == "id-1")
    {
        console.log("Input with ID of id-1 accessed");
    } else
    {
        console.log("Input with a different ID accessed");
    }
  }
);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1>Chat#index</h1>

<ul id="chat_area">
</ul>
<input id="id-1" class='form-control' type="text">

07-24 17:55
查看更多