background-color随jquery而变化

时间:2013-02-02 02:42:37

标签: jquery ruby-on-rails

这是我自己编写jQuery的第一次尝试。我试图这样做,当我将鼠标悬停在一个名称的实例上时,背景会变为白色以及该名称的所有其他实例。每个名称都有一个唯一的数据ID,对于它的所有实例都是通用的。

我认为我的jQuery错误地在person = this.data("id");我试图分配悬停的元素的数据属性,然后用该数据属性更改所有元素的背景。不确定我是否接近。

错误如下:

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

timeline

<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>

2 个答案:

答案 0 :(得分:2)

你非常接近!

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

hover将两个函数作为参数,因此您的mouseout恰好在以下情况下执行相反的操作:

$("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");
 });

答案 1 :(得分:1)

问题是您没有正确获取具有特定data-id值的元素,问题是$data(person)。使用此:

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

您必须将current的值注入属性Equals选择器,例如this guy

相关问题