开发者

Jquery: finding element with classname stored in variable

(Edited with more detail just in case someone else has a similar question)

I've got an image map which needs to reveal a div on rollover of a hotspot. I've given my areas on the image map classes, and using jQuery want to reveal it's corresponding div, e.g.,

area shape="rect" coords="601,31,723,107" href="#" alt="Some Loc开发者_运维技巧ation" class="some-location"

Each area has a different location and therefore different classname.

I'm not sure how to reference an element with its classname stored in a variable? For example, the code I currently have to get the class name on hovering over an area on the image map is:

var hotspot = $(this).attr("class");

Now I want to do something like:

$(div.hotspot).show();

The above is not working - could someone point me in the right direction?


Use string concatenation:

$("div." + hotspot)

Obviously this only works if hotspot only contains one class (see Reigel's comment). If it contains more classes, you have to replace the white spaces by a dot:

$("div." + hotspot.replace(' ', '.'))

(assuming that multiple white spaces between class names get trimmed automatically but I am not sure about that, otherwise you have to use the regular expression /\s+/)


$('.' + hotspot).show();

since your variable hotspot contains a class string, you need to pass it as a string selector.

It does not make much sense anyway, since you would access the same element from which you received that class name. If you already queried that element once, you can (and should!) store / cache the jQuery object into a variable and access it from there again.


You need to pass a string argument to $() you missed the quotes in your example. you need to do $('.hotspot').show() You might also have var c = '.hotspot';$(c).show()


$("#divid").find(hotspot);

You can use this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜