开发者

Dynamically Add 1 to id/class on appended div with jQuery

I am trying to add 1 to any newly appended id/class:

jQuery:

$(function(){
$("#add-new-student").click(function() {

$("ul#student-list").append('<li class="student3"/>Student</li>');
$("div#student-courses").append('<div id="student3" class="student-information">'
+ '<div id="student3-enrolled-courses">'
+ '<span class="english">English</span>'
+ '<span class="technology">Technology</span&开发者_如何学编程gt;'
+ '</div>'
+ '</div>'
);

});
});

HTML:

<input type="submit" id="add-new-student" value="Add New Student">

<ul id="student-list">
<li class="student1"/>Student</li>
<li class="student2"/>Student</li>
</ul>

<div id="student-courses">
<div id="student1" class="student-information">
<div id="student1-enrolled-courses">
<span class="english">English</span>
<span class="technology">Technology</span>
</div>
</div>

<div id="student2" class="student-information">
<div id="student2-enrolled-courses">
<span class="english">English</span>
<span class="technology">Technology</span>
</div>
</div>
</div>

I set up two fiddles:

http://jsfiddle.net/KHfyY/ uses after instead of append and finds the div.student-information:last

http://jsfiddle.net/KHfyY/1/ uses the code here with append for both

Whichever one is best for this should be the one we can use.

If there are no students, then the first class/id's should be student1. If there are students as in the code, it should increment it by 1 based on the last student number. Any idea how this can be done?


Try this:

$(function(){
    $("#add-new-student").click(function() {
        var studentList = $("ul#student-list");
        var currentCount = $("li", studentList).length + 1;
    studentList.append('<li class="student' + currentCount +'">Student</li>');
    $("div#student-courses").append('<div id="student' + currentCount +'" class="student-information">'
    + '<div id="student' + currentCount +'-enrolled-courses">'
    + '<span class="english">English</span>'
    + '<span class="technology">Technology</span>'
    + '</div>'
    + '</div>'
    );
    });
});

Working example @: http://jsfiddle.net/KHfyY/5/


Updated

http://jsfiddle.net/KHfyY/7/

Like this?

Just set the variable n in advance based on how many students you have at the beginning.

In this example, the n is calculated automatically by counting the student already present in the list.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜