GetJSON方法具有相同的值

时间:2018-11-29 15:20:07

标签: javascript jquery json

下面是我的代码

$(document).ready(function () {
    $.getJSON("data.json", function (data) {
        var user_Data = "";
        $.each(data, function (key, value) {
            user_Data += '<p class="user">' + value.name + '</p>';
            console.log(data[key].name);
        });
        $("#usernames").append(user_Data);
    });
    
    
    $(document).on('mouseover', '.user', function () {
        $.getJSON("data.json", function (data) {
            var hover_Data = "";
            var user = $(".user");
            for (var i = 0; i < user.length; i++) {
                $.each(data, function (key, value) {
                    if ($(user[i]).text() == data[key].name) {
                        hover_Data = '<p class="hover_user">' + value.name + '</p>';
                    }
                });
                
            }
            
            
            $("#hover_details").append(hover_Data);
        });
    });
});

当用户将鼠标悬停在一个名称上时,我想在鼠标悬停时显示相同的名称,但是无论我将鼠标悬停在哪个名称上,我都会得到相同的名称,如果if语句出问题了?

2 个答案:

答案 0 :(得分:0)

                                             //pass in the event
$(document).on('mouseover', '.user', function(e) {
  $.getJSON("data.json", function(data) {
    var user = $(e.target); //use the user that was hovered
                            //don't find all of them
      $.each(data, function(key, value) {
        if (user.text() == data[key].name) {
          $("#hover_details").append('<p class="hover_user">' + value.name + '</p>');
        }
      });
  });
});

答案 1 :(得分:0)

不要进行ajax调用。...只需获取当前用户元素的文本

$(document).on('mouseover', '.user', function () {
    var $p = $('<p class="hover_user">').text( $(this).text() );
    $("#hover_details").append($p);      
});