I'm new to stackoverflow and jQuery altogether, so I'm having a little trouble making a simple function.
I basically have in my website a random number of links with id "filtro" + "some number"
, and I want to write only one code to the action of clicking in any of them (that would later impact on the class with same "filtro" + "some number").
Eg.: Click "#filtro3", do something on ".filtro3".
The problem is, I don't know how to write the string in jQuery for "any number". I'm thinking about doing something like this:
$(function () {
$("#" + "filtro" + SOME NUMBER).click(function () {
//Do something with the element "." + "filtro" + SOME NUMBER
});
});
Any ideas? Thank you!!
Ps.: This is my first question, and I apologize if I made any mistakes.
SOLVED. dystroy's solution worked like a charm.
For future reference to others, I was making this code to make a simple filter menu for a picture gallery. This way I could hide/show pictures of certain topics.
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.
Given an HTML document and the task is to select the elements with different ID's at the same time using JQuery. Approach: Select the ID's of different element and then use each() method to apply the CSS property on all selected ID's element.
Try this: $('element'). attr('id', 'value');
You seem to want
$(function () {
$("[id^=filtro]").click(function () {
var num = this.id.slice(6);
// if there is a risk of ambiguity, you might check here that +num==num
var $elem = $('.filtro'+num);
...
});
});
Explanations :
$("[id^=filtro]")
uses the starts with selector to select all elements whose id starts with "filtro"this.id.slice(6);
takes the part of the id starting after the sixth character. Maybe it would be clearer as this.id.slice('filtro'.length)
or this.id.substring('filtro'.length)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With