动态添加事件的正确方法是什么?

编程入门 行业动态 更新时间:2024-10-22 15:31:24
本文介绍了动态添加事件的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

目标是,当我专注于最后一个文本行时,在其下方出现另一个文本行.然后在一定数量的行上禁用此功能. 我似乎无法弄清楚这里出了什么问题:

The goal is, when I focus on the last text line, another one appears below it. Then disable this at a certain number of lines. I can't seem to figure out what is wrong here:

$(document).ready(function() { lineCount = 0; $("form#qc").delegate("input:text:last-child", "focus", newTextLine); }); function newTextLine() { newLine = ("<div id='ansInput{0}'>Answer {0}: <input type='text' name='ans1' /></div><!--ans1-->").format(lineCount); currentDiv = ("#ansInput{0}").format(lineCount); $(currentDiv).after(newLine); lineCount = lineCount++; }

这是HTML页面:

<form id="qc" name="qc"> <h2>Create New Question!</h2> <div id="ansInput0">Question: <input type="text" name="Question" /></div><!--question--> <input type="submit" value="Submit" /> </form>

我得到一个非常非常奇怪的结果:每次出现两行,并且所有索引都为0,并且都响应事件处理程序,该事件处理程序仅适用于最后一行... 任何想法代码有什么问题吗?

I get a very very weired result: each time two lines appear and all have index of 0 and all respond the event handler that is suppose to work only for the last one... Any ideas what's wrong with the code?

JSfiddle

欢迎提供任何有关如何使代码更智能的建议!

Also any advice on how to make the code smarter is welcome!

推荐答案

如上所述,您的代码中存在一些问题. 我会这样尝试: 克隆最后一个div,更改id并清除输入的值:

As said, there are some problems in your code. I'd try it like this: Cloning the last div, changing the id and clearing the value of the input:

$(function() { $("#qc>div:last-of-type>input").live('focus', function() { $(this).parent().after($(this).parent().clone().attr('id', 'ansInput' + $('#qc>div').length).find('input').val('').end()); }); });

jsfiddle/7enNF/1/

  • input:text:last-child选择作为其父级中最后一个子元素的输入.因此它将选择所有输入,因为每个输入都是ansInput div中唯一的(因此是最后一个)子项.
  • #qc> div:last-of-type> input选择最后一个div中的输入.我使用了last-of-type,因为last-child与div不匹配,因为Submit按钮是表单的最后一个孩子
  • 结束是必要的,因为我选择了div,然后选择了带有"find('input')"的输入以清除值.如果我以这种方式离开它,它将只插入输入(而不是div).因此,end()再次从输入返回到div,以便将div插入.

我希望这不会太令人困惑! :)

i hope this wasn't too confusing! :)

更多推荐

动态添加事件的正确方法是什么?

本文发布于:2023-07-17 02:44:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128579.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   事件   方法   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!