I have a menu – each menu item has a class name. When I click on the menu item I am using JQuery to find a div with a matching ID name. The problem is that the search isn’t strict. If something has a class name like elo-1 and I have div IDs name elo-1 and elo-11 there is no way (the way I am doing this) to get just elo-1.
I would like to get an exact match. I would like to click on elo-1 and only get elo-1, not elo-1, elo-11, elo-12, etc. Anyone have any ideas?
Here is teh code I am using:
$(document).ready(function() {
var myLayoutId = $(this).attr("layoutId");
$("#start_page").show().siblings().hide();
$("#navBar").hide();
$("#refs").hide();
$("li").click(function() {
var thisID = $(this).attr("class");
$("#mainBdy div:#"+thisID).show().siblings().hide();
$('#mainBdy div[id^="'+thisID+'"]').show();
$("#mainBdy div:#"+thisID).css("width","30%");
$("#mainBdy div:#"+thisID).css("margin-left","-80px");
$("#mainBdy div:#"+thisID).css("margin-top","-50px");
$("#mainBdy div:#"+thisID).css("float","left");
});
$("#start_page_accept").click(function() {
$("#navBar").show();
$("#refs").show();
$("#start_page").hide().next().show();
});
$("#menu").collapsible({
effect: "slide", // The effect to use when expanding and collapsing the menu.
initialCollapse: true // When true, collapses the menu when the page loads.
});
});
Modify your selector to avoid starts-with matching:
This matches anything that starts with your value, which is not what you want:
This matches only those items whose id attribute is equal to your value.
Additional Suggestions
Note also that you’re binding to individual list items:
This could become tasking to your app since you’re adding an event handler for every new list item that is placed on the page. Event Delegation is a far better approach, and consists of adding one event handler to the ancestor element, using event-bubbling to respond to events on nested items.
Suppose this was our markup (toss in another 100 list items for good measure), the following would be our event-delegation instruction:
Anytime a click event occurs on, or within our
#listelement, we will evaluate whether the target (the element that received the click) matches our selectorli. If it does, we trigger our function – otherwise, we ignore it and let it bubble up the DOM.