As mentioned in comments id
should be used as a unique identifier. To help enforce this your HTML Mark-up will not be valid if there are repeating id=
attributes with the same value on the same page.
When it comes to deciding what to use, consider how the element will be selected within the JS/jQuery. Is the jQuery going to use that element and ONLY that element when processing? If so, then id
is fine, if the element is part of a group and you would like to re-use the jQuery when something happens to any item in that group then using a class=
is more appropriate.
id
and class
can also be used together. Say you want something to happen whenever a group is clicked, but also want to know exactly which item in the group was clicked, you could do something like:
HTML:
<div id="1" class="clickable"> Click Here!! </div>
<div id="2" class="clickable"> Click Here!! </div>
<div id="3" class="clickable"> Click Here!! </div>
<div id="Clicked"></div>
jQuery:
$('.clickable').click(function(){
// Reset the color of all clickable elements
$('.clickable').css("background-color","white");
// Display which element we clicked
$('#Clicked').html('You Clicked Div: ' +this.id);
// Set the background color of the clicked element
$(this).css("background-color","lightgreen");
});
JSFiddle
In this example the first three divs are part of a 'group' by using a common class="clickable"
in the jQuery I can then trigger an event for any of these elements without having to duplicate code.
The .clickable
selector is a Class Selector which means that it will be triggered for any element with class="clickable"
, this does not have to be a div
.
The #Clicked
selector is a Id Selector which will select the first element matching id="Clicked"
Once the .click
event has been triggered the this.id
can be used to get the exact element we clicked on out of the three, $(this)
can be used to manipulate the clicked element and $('.clickable')
can be used to manipulate all elements grouped by the class
attribute.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…