动态添加事件的正确方法是什么? [英] What is the right way dynamically adding events?

查看:70
本文介绍了动态添加事件的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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());
    });
});

http://jsfiddle.net/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! :)

这篇关于动态添加事件的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆