【问题标题】:set focus on input and change li background color将焦点放在输入上并更改 li 背景颜色
【发布时间】:2020-06-02 08:06:52
【问题描述】:

这个函数允许我创建新的 li 元素并将其附加到我当前的待办事项列表中。

var newListElement =
  "<li>" +
  '<input type="checkbox"/>' +
  "<label>" +
  '<input [type="text"] placeholder="Insert your new task here"/>' +
  "</label>" +
  '<div class="arrow-btn"></div>' +
  "</li>";

$("ul.todo-list").append(newListElement);

在这个函数中,我想将光标设置到我的输入文本字段,并希望在新创建 li 元素时将其背景更改为灰色。但是每当我创建一个新的 li 元素时,li 元素的颜色不会改变,我也不能将光标自动设置到输入字段。只有当我用鼠标在 li 元素上新创建的输入字段中手动单击时,li 元素的背景才会发生变化。

		
//change last added list element to grey
$('input:text').focus(function () {
   setEditModeItem($(this).closest('ul.todo-list > li'));
});

我的问题是有没有办法将焦点动态设置到输入字段并检查它是否有焦点?

【问题讨论】:

  • 我相信你需要使用事件委托,所以使用这个$('ul.todo-list').on("focus","input:text",function () {
  • 正如@CarstenLøvboAndersen 所说,您必须使用事件委托,因为您是从javascript 添加 li ,因此不会触发焦点事件。但是,如果你按照他说的去做就可以了

标签: javascript html jquery focus


【解决方案1】:

您可以通过在所选元素上调用.focus()方法在jQuery中触发焦点,我添加了CSS背景红色以突出显示焦点上的输入,注意您可以使用Template literals连接字符串,这是一个有效的sn- p:

var newListElement = `<li>
  <input type="checkbox"/>
  <label>
  <input [type="text"] placeholder="Insert your new task here"/>
  </label>
  <div class="arrow-btn"></div>
  </li>`;

$("ul.todo-list").append(newListElement);
// this is how to trigger focus on input:
$("ul.todo-list li:last-child").find("input").focus();
//change last added list element to grey
$("input:text").focus(function () {
  //setEditModeItem($(this).closest('ul.todo-list > li'));
});
ul.todo-list input:focus {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="todo-list"></ul>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 2013-01-02
    • 2018-04-14
    • 2021-03-07
    相关资源
    最近更新 更多