Dynamically appending text lines

2019-09-01 16:46发布

The goal of the code is to create a new input line each time the last line is focused, until a certain amount of lines. I was offered this solution which works great:

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

but I also want to change each time the text before the line, so clone won't cut it

I modified it to write a pre-ready HTML line, but it doesn't work:

function questionsForm() {
    $("#qc>div:last-of-type>input").live('focus', function() {

        lineNum = $('#qc>div').length
        newLine = ("<div id='ansInput{0}'>Answer {0}: <input type='text' name='ans{0}' /></div><!--ans1-->").format(lineNum);

        if ($('#qc>div').length <= 4) { 
            $(this).parent().after(newLine);
        }
    });
}

(the .format method is predefined)

I would like to understand why my code isn't working, and how to chamge it, but not completely different solutions (unless of course my code has some fundamental errors..)

1条回答
家丑人穷心不美
2楼-- · 2019-09-01 17:01

you are missing a semicolon after lineNum = $('#qc>div').length

why is that code in the questionsForm() function?
you could just place it in the jquery ready function $(function(){ ... });

Also what does your format function look like?

查看更多
登录 后发表回答