If i have elements such as this
Do not create markup that contains elements with duplicate IDs. This will break things, and you will be mauled by a velociraptor faster than you can say "goto".
Use classes instead:
<img src='0.jpg' id='images' />
<img src='...' class='myEle' />
<img src='...' class='myEle' />
then...
$(document).ready(function() {
$('.myEle').live('mouseup', function () {
$('#images').attr("src", myEle.getNumber() + ".jpg");
});
});
"How do i know which image is pressed?"
Use the this
keyword:
$(document).ready(function() {
$('.myEle').live('mouseup', function () {
$('#images').attr("src", $(this).attr('src'));
});
});
...I think that's what you're looking for.
If multiple elements will share a certain property, you should assign class to them instead of id. So the resulting jquery code will look something like:
$('.myEle').mouseup();
ID is to be used to uniquely identify elements.
It is true that having multiple elements with the same id
is incorrect. However it is pretty easy to generate such code in general-purpose frameworks, for example in Django one may have more than one forms in a single view with the same field auto_id
. Thus it would be nice to have jQuery function which selects all of these elements so client-side Javascript code can check the length of returned list and trigger a client-side error / warning in such case.
Also do not forget that the value of id
has to be escaped in CSS query. While recent versions of Chrome / Firefox have native support of CSS.escape()
, IE may require a polyfill: https://github.com/mathiasbynens/CSS.escape
$.id = function(id) {
// FF 54 generates warning when empty string is passed.
if (typeof id !== 'string' || id === '') {
return $();
} else {
// Support multiple ID's to detect content bugs.
return $(document.querySelectorAll('#' + CSS.escape(id)))
}
};
If you've inherited code so horrible that you can only work with the faulty output, use jQuery("[id=theidthatshouldbeaclassinstead]")
or jQuery("[id*=theidthatshouldbeaclassinstead]")
if there are multiple ids for some reason.