简体   繁体   中英

background-color changes with jquery

This is my first attempt at writing jQuery myself. I'm trying to make it so when I hover on an instance of a name, the background changes to white as well as all the other instances of that name. Every name has a unique data-id that is common to all it's instances.

I think my jQuery goes in err at person = this.data("id"); I'm trying to assign the data attribute of the element hovered over and then change the background of all elements with that data attribute. Not sure if I'm even close.

Errors are as follows:

Uncaught TypeError: Object #<HTMLDivElement> has no method 'data' localhost:60
  (anonymous function) localhost:60
  jQuery.event.special.(anonymous function).handle jquery.js:3353
  jQuery.event.dispatch jquery.js:3062
  elemData.handle.eventHandle

时间线

<div id="center">
    <% @instances.each do |instance| %>
        <div class="instance" data-id="<%= instance.person.id %>" style="top:<%=top_helper(instance)%>px; left:<%= left_helper(instance) %>px; width:<%= width_helper(instance) %>px;">
            <span><%= instance.person.first_name %>, <%= instance.rank %></span>
        </div>
    <% end %>
</div>

<script>
    $("div#center").ready(function(){
        var person 
        $("div.instance").hover(function(){
            person = this.data("id");
            $data(person).css("background-color","white");
        });
    });
</script>

You're very close!

$("div.instance").hover(function(){
    person = $(this).data("id");
    $('div[data-id="' + person + '"]').css("background-color","white");
 });

hover takes two functions as arguments, so your mouseout just does the opposite right after:

$("div.instance").hover(function(){
    person = $(this).data("id");
    $('div[data-id="' + person + '"]').css("background-color","white");
 },
 function(){
    person = $(this).data("id");
    $('div[data-id="' + person + '"]').css("background-color","gray");
 });

The problem is that you are not getting correctly the elements with the specific data-id value, the problem is $data(person) . Use this:

$("div#center").ready(function(){
    var person 
    $("div.instance").hover(function(){
        person = $('this').data("id");
        $('div[data-id="' + person + '"]').css("background-color","white");
    });
});

You have to inject the value of current into an attribute Equals selector, like this guy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM