Get the suffix of a dynamically selected id within a hover method
I have the following JQuery selector with a hover method attached to it:
$("a[id^='foo']").hover(
function () {
$(this).css("color", "#eeeeee");
},
function () {
$(this).css("color", "#ffffff");
}
);
However,开发者_StackOverflow中文版 I want to alter a td decoration underneath the links with the 'foo' prefixes on their id's, which have a 'bar' prefix. For clarification: foo1, foo2, foo3 and bar1, bar2, bar3. How can I figure out what id is currently in effect and use its corresponding suffix within the same hover method?
Technically in semi-pseudo code I want to achieve this result
$("a[id^='foo']").hover(
function () {
$(this).css("color", "#eeeeee");
// var x = charAt($(this).id.length-1)
// $("#bar"+x).css("color", "#eeeeee");
},
function () {
// ...
}
);
I tried variations with $this.id, but I get undefined values.
Thanks for the help!
Use this.id
, not $(this).id
. Technically $(this).attr("id")
would also work, but is not a great idea because it is going through several levels of jQuery indirection to achieve the same result.
Explanation: this
is a native DOM element, with all the usual properties and methods (e.g. id
, className
, and addEventListener
to name a few). $(this)
is the jQuery object created from that DOM element, which only has jQuery methods, not any of the original properties.
精彩评论