开发者

Issue with changing child div style using jQuery (via class selector)

this is more curiosity question rather than a problem)

With my Rails 3 application I generate a lots of blocks, which contain div elements. One block looks like this:

<div class="link_div">
        <%= link_to ... %>
        <div class="ranking">
        <%= link_to ... %>
        <%= link_to ... %>
        <%= link_to ... %>
    </div>
</div>

And now Im trying to toggle "ranking" div visibility on mouseOVER. It wasnt so easy, cause I`m a newbie to jQuery. I开发者_如何学JAVA was trying a lots of css accessors, but finnally I have found a solution look like this:

$('.link_div').hover(
      function () {
        $(this).children('.ranking').css('display','block');
      },
      function () {
        $(this).children('.ranking').css('display','none');
      }
);

So the question is: "Why this solution doesn`t work?":

$(this).children()[1].css('display','block');

Alert says that chilren()[1] gives me div object, but it doesn`t have .css() method. Why?

alert($(this).children()[1]) // => "[object HTMLDivElement]"


Why are you doing this in javascript? This is clearly something that belongs in css. You will get a lot clearer code, A better separation between markup, content and behavior and a huge performance gain.

example


Here is a demo of a very simple way of showing/hiding the ranking <div> when hovering over the <div class="link_div">

The selector $('.ranking', this) matches all elements with class .ranking inside the current element (the context) and applies the show() function to them.

As others have already answered, your problem is that you have dereferenced the jQuery object with the [1] and you have a raw DOM object. You need to call functions on the jQuery objects in this case.


Because it's an object, not a jQuery object (so, doesn't have jQuery methods/properties).

Try $($(this).children()[1]).css('display','block');

Or, even tidier, just remove the [1]:

$(this).children().css('display','block');


[1] is giving you the div object, NOT a jquery object. .css is a jquery method and must be used on a jquery object.

Try this instead:

$(this).children().eq(1).css('display','block');

or

$(this).children(":eq(1)").css('display','block');

and even better, use show() and hide() instead of setting the display.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜