1

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

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

错误如下:

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

2 回答 2

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");
 });
于 2013-02-02T02:47:52.127 回答
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 选择器中,就像这个人一样

于 2013-02-02T02:52:32.053 回答