开发者

What is the right way dynamically adding events?

开发者 https://www.devze.com 2023-03-08 16:52 出处:网络
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.

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++;
}

this is the HTML page:

<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>

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!


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 selects inputs which are the last child element in their parent. so it would select all the inputs, because each of them is the only (therefore last) child in the ansInput div
  • #qc>div:last-of-type>input selects the input in the last div. i used last-of-type because last-child wouldn't match the div, because the submit button is the last child of the form
  • the end is necessary because i select the div, then i select the input with "find('input')" to clear the value. if i'd leave it that way it would only insert the input (not the div). So the end() to get back from the input to the div again so that the div will be inserted.

i hope this wasn't too confusing! :)


I see a couple problems here. First of all, I don't see what the scope is on your lineCount variable based on the code you've provided. Second, just because you're adding an event handler to the new elements you're creating, doesn't mean you're removing it from the old one.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号