0

目标是,当我关注最后一行文本时,另一行会出现在其下方。然后在一定数量的行禁用它。我似乎无法弄清楚这里出了什么问题:

$(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并且都响应事件处理程序,该事件处理程序应该只适用于最后一个......有什么想法代码有什么问题吗?

JSfiddle

也欢迎任何关于如何使代码更智能的建议!

4

2 回答 2

1

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

$(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 不匹配,因为提交按钮是表单的最后一个子项
  • 结束是必要的,因为我选择了 div,然后我用“find('input')”选择输入来清除值。如果我让它这样,它只会插入输入(而不是 div)。所以 end() 再次从输入返回到 div 以便插入 div。

i hope this wasn't too confusing! :)

于 2011-05-27T16:45:00.687 回答
0

我在这里看到了几个问题。首先,根据您提供的代码,我看不到 lineCount 变量的范围。其次,仅仅因为您正在向正在创建的新元素添加事件处理程序,并不意味着您正在从旧元素中删除它。

于 2011-05-27T16:39:56.207 回答