1

So, I'm creating a webpage where new elements are dynamically created by the user, and as they are made, each element object is added to an array to keep track of them. The thing is, that when someone closes the element, I want it to be removed from the array; the only way I can think of is to give an ID equivalent to the index in the array to each element. I feel as if this could get messy and/or be bad practice. Is there any alternative? Or is this ok to do?

4

3 回答 3

2

It's not about dynamic vs not dynamic.

An ID should be given to an element for one reason, if it is unique. If only one of that element type (By "type" I mean semantically meaning type, not tagname or such. For instance, there can be multiple sidebars, or headlines, but only one #mainNav or #generalWrapper).

Giving an ID to every single element you create dynamically is, by definition, wrong. Since you most likely create very similar elements, in which case, a class name is more appropriate.

If you want a way to track them, you can always use data-*= attributes with whatever custom data you want. For instance: data-id=1

于 2013-01-06T21:48:58.310 回答
2

There's a big debate about over-use of ID's.

My suggestion would be to use a data attribute, something like:

<li data-id="54">My element</li>

Then you can easily manipulate the element (remove, modify, etc) using Javascript. jQuery has the data() method for instance - http://api.jquery.com/jQuery.data/

My main argument against using a class or id is that you're (in this instance) looking for information about an element for a specific function, whereas a class or id is better suited for distinguishing the element on a more global level.

于 2013-01-06T21:49:08.700 回答
0

You could wait until the user is finished adding or removing the elements and then use something like jQuery's $.each function. For example if you want to collect the value from a series of inputs that a user added to a div you could simply do

var myArray = [];
$('#mydiv input').each(function(){
    //Do something here with each of the inputs
    myArray.push($(this).val());
});

If you want to simply add some sort of attribute to them you could still use this same function

$('#mydiv input').each(function(index){
    //Do something here with each of the inputs
    $(this).attr('data-id', index);
});

I hope I answered your question for you as I am not sure what you are trying to use that array for. I assumed for some sort of submission at some point.

于 2013-01-06T21:58:59.810 回答