最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Adding ID to LI Javascript - Stack Overflow

programmeradmin7浏览0评论

So I have this following code set up to create an li element when someone inputs something into a box. I also want the li element to contain a unique ID which will begin with list-Item0 and go to list-Item1, etc with every li created when someone types into the box and adds the item.

Any idea how I would go about doing this? I don't know what JQuery is as I am a plete beginner so am looking for something extremely basic which I can implement in this code.

Here's what I have so far:

function addItemFunction() {
    document.getElementById("itemList").innerHTML=document.getElementById("itemList").innerHTML + '<li>' + addNewBox.value + '</li>';  
}

So I have this following code set up to create an li element when someone inputs something into a box. I also want the li element to contain a unique ID which will begin with list-Item0 and go to list-Item1, etc with every li created when someone types into the box and adds the item.

Any idea how I would go about doing this? I don't know what JQuery is as I am a plete beginner so am looking for something extremely basic which I can implement in this code.

Here's what I have so far:

function addItemFunction() {
    document.getElementById("itemList").innerHTML=document.getElementById("itemList").innerHTML + '<li>' + addNewBox.value + '</li>';  
}
Share Improve this question edited Jul 13, 2015 at 23:56 Michael0x2a 64.6k32 gold badges189 silver badges240 bronze badges asked Jul 13, 2015 at 23:49 revalerstrasserevalerstrasse 11 silver badge1 bronze badge 1
  • 1 @DeanRather—no, don't do that. Much better for the OP to learn plain JS, then make his/her own decision about which library (if any) best suits their needs for a particular purpose. – RobG Commented Jul 14, 2015 at 0:33
Add a ment  | 

2 Answers 2

Reset to default 6

Simply keep a counter for the ID outside your function, create an <li> element, set the ID and content, increment the counter and append the element to your itemList.

var listItemCounter = 0;        

function addItemFunction() {
    var li = document.createElement('li');
    li.id = 'list-Item' + listItemCounter++;
    li.innerHTML = addNewBox.value;

    document.getElementById('itemList').appendChild(li);
}

As an extension to Phil's answer, you can avoid the global counter by keeping it in a closure:

var addItemFunction = function () {
    var listItemCounter = 0;        

    return function () {
        var li = document.createElement('li');
        li.id = 'list-Item' + listItemCounter++;
        li.innerHTML = addNewBox.value;

        document.getElementById('itemList').appendChild(li);
    };
}());
发布评论

评论列表(0)

  1. 暂无评论