开发者

jQuery Selector For .append'd Content

开发者 https://www.devze.com 2023-03-11 20:07 出处:网络
I have the following jQuery function to add inputs on an anchor click: $(\"a#addrec\").click(function () {

I have the following jQuery function to add inputs on an anchor click:

$("a#addrec").click(function () {
    var max = $("span#recommends input[id^='rec']:last").attr("id").substr(3, 1);                     开发者_运维问答              
    var next = max + 1;
    $("span#recommends").append('<input type="text" id="rec'+next+'" name="rec[]" placeholder="Joe\'s Nightclub" style="margin-left: 175px; margin-top: 10px;" /><div id="rec'+next+'err" class="err"></div><br style="clear: both;" />');
    return false;
});

and, I would like to id them sequentially, (ie. rec1, rec2, rec3, etc.) but I'm obviously doing something wrong. The input is added, but the selector to find the last input only finds the last non-appended input, rather than the last of the set of existing and appended inputs.

I've searched, and found this thread:

How to get reference to jQuery selector for content just added via manipulation method?

but I don't quite see how this resolves my issue.

I guess my question, in a nutshell is, "How do I select the newly appended inputs each time the anchor is clicked?"


You have to parseInt (demo: http://jsfiddle.net/UtA5E/)

$("a#addrec").click(function() {
    var max = $("span#recommends input[id^='rec']:last").attr("id").substr(3, 1);
    var next = parseInt(max) + 1;
    $("span#recommends").append('<input type="text" id="rec' + next + '" name="rec[]" placeholder="Joe\'s Nightclub" style="margin-left: 175px; margin-top: 10px;" /><div id="rec' + next + 'err" class="err"></div><br style="clear: both;" />');
    return false;
});

Before it was doing '1' + 1 which is equal to 11 and then 111 etc etc.


Store jQuery's interpretation of the DOM element in a var and work with that instead of directly accessing the DOM each time:

var $records = $("span#recommends");

$("a#addrec").click(function () {
    var max = $($records + " input[id^='rec']:last").attr("id").substr(3, 1);                                   
    var next = max + 1;
    $records.append('<input type="text" id="rec'+next+'" name="rec[]" placeholder="Joe\'s Nightclub" style="margin-left: 175px; margin-top: 10px;" /><div id="rec'+next+'err" class="err"></div><br style="clear: both;" />');
    return false;
});
0

精彩评论

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