【问题标题】:jQuery fill the prepared HTML div dynamically with JSON datajQuery 用 JSON 数据动态填充准备好的 HTML div
【发布时间】:2016-10-19 11:04:25
【问题描述】:

我有什么:

  1. 带有 ID、姓名、职位、部门和地址的 JSON。
  2. 同样的 JSON 有超过 1000 名随机员工循环到一个表中。
  3. 每个人都有一个自定义属性 (user_id) 和相同的 CSS 类用于悬停。
  4. 当鼠标悬停在一名员工身上时,一个隐藏的准备好的和样式化的 div 用于提供信息。

我需要什么:

  1. 当我将鼠标悬停在某个员工上时,我需要显示所有员工信息,例如姓名、职位、部门和地址。请记住,悬停是有效的,但信息仍然是静态的。所以基本上,我的逻辑是自定义 attr user_id 和 JSON id 匹配 = 填充 html。 我该怎么做?

var xmlhttp = new XMLHttpRequest();
var url = "https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/189576/1743369/lDhMee0RoA1IO5D/generated.json";
var employees;
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        employees = JSON.parse(this.responseText);
        write(employees);
    }
};
xmlhttp.open("GET", url, true);
xmlhttp.send();


function write(arr) {
    var i;
    var out = '<table>';
    for(i = 0; i < arr.length; i++) {
        out += '<tr>';
        out += '<td class="hoverKartX" user_id="' + arr[i].id + '">' + arr[i].name + '</td>';
        out += '<td>' + arr[i].position + '</td>';
        out += '</tr>';
    }
    out += '</table>';
    document.getElementById('employees').innerHTML = out;
}

$(function() {
  var moveLeft = 20;
  var moveDown = 10;

  $('.hoverKartX').hover(function(e) {
    //$(this).parent().find(".hoverKart").show();

    $(".hoverKart").show();
  }, function() {
    $('.hoverKart').hide();
  });

  $('.hoverKartX').mousemove(function(e) {
    $(".hoverKart").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);

    // preventing 'falling' to the right on smaller screen
    if ($(".hoverKart").position()['left'] + $('.hoverKart').width() > $(window).width()) {
        $(".hoverKart").css("left", $(window).width() - $(".hoverKart").width());
    };

    // preventing 'falling from the bottom of the page'
    if ((e.pageY + moveDown + $(".hoverKart").height()) > ($(window).scrollTop() + $(window).height())) {
      $(".hoverKart").css("top", $(window).height() - $(".hoverKart").height() + $(window).scrollTop());
    }
});


});
.hoverKart {
    position: absolute;
    width: 400px;
    height: 220px;
    border-radius: 25px;
    border: 1px solid #999;
    z-index: 1;
    display: none;
    background: #fff;
}
<!-- hidden div-->
<div class="hoverKart">
    <div class="container">
        <div class="cardTop"><p><!-- JSON DATA (ID) --></p></div>
            <div class="imgHolder">
                <img class="employee" src="img/img.jpg" alt="employee image">
                <img class="eLogo" src="img/logo.jpg" alt="logo">
            </div>
            <div class="eInformation">
                <p class="eName"><!-- JSON DATA (NAME) --></p>
                <p class="ePos"><!-- JSON DATA (DEPARTMENT) --></p>
            <div class="eDep">
                <img src="img/icons-dep/5.png" alt="department logo">
            </div>
            <p class="eOp">Operations</p>
            <p class="eOp2"><!-- JSON DATA (ADDRESS) --></p>
            </div>
    </div>
</div>

<div id="employees"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【问题讨论】:

  • 你可以查看我的答案。我为您的代码创建了一个工作小提琴。

标签: javascript jquery json


【解决方案1】:

我已经更新了你的代码并创建了一个小提琴:

检查working Fiddle

$(function(){
var xmlhttp = new XMLHttpRequest();
var myGlobalJson;
var url = "https://s3-eu-west-1.amazonaws.com/uploads-eu.hipchat.com/189576/1743369/lDhMee0RoA1IO5D/generated.json";
var employees;
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        employees = JSON.parse(this.responseText);
        myGlobalJson = employees;
        write(employees);
    }
};
xmlhttp.open("GET", url, true);
xmlhttp.send();




function write(arr) {
    var i;
    var out = '<table>';
    for(i = 0; i < arr.length; i++) {
        out += '<tr>';
        out += '<td class="hoverKartX" user_id="' + arr[i].id + '">' + arr[i].name + '</td>';
        out += '<td>' + arr[i].position + '</td>';
        out += '</tr>';
    }
    out += '</table>';
    document.getElementById('employees').innerHTML = out;
    bindMethods();
}

//$(function() {
function bindMethods(){
  var moveLeft = 20;
  var moveDown = 10;

  $('.hoverKartX').hover(function(e) {
    //$(this).parent().find(".hoverKart").show();
        var currentUserId = parseInt(($(this).attr('user_id')));
    //console.log(myGlobalJson);
    //console.log(typeof  parseInt($(this).attr('user_id')));
    $.each(myGlobalJson, function(i, item) {
      //console.log($(this).attr('user_id'));
    if(item.id === currentUserId){
      $(".hoverKart .cardTop").html(item.id);
      $(".hoverKart .eName").html(item.name);
      $(".hoverKart .ePos").html(item.position);
      $(".hoverKart .eOp2").html(item.address);  
      return false;
    }
});

    $(".hoverKart").show();
  }, function() {
    $('.hoverKart').hide();
  });

  $('.hoverKartX').mousemove(function(e) {
    $(".hoverKart").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);

    // preventing 'falling' to the right on smaller screen
    if ($(".hoverKart").position()['left'] + $('.hoverKart').width() > $(window).width()) {
        $(".hoverKart").css("left", $(window).width() - $(".hoverKart").width());
    };

    // preventing 'falling from the bottom of the page'
    if ((e.pageY + moveDown + $(".hoverKart").height()) > ($(window).scrollTop() + $(window).height())) {
      $(".hoverKart").css("top", $(window).height() - $(".hoverKart").height() + $(window).scrollTop());
    }
});
}
//});
});

现有代码中存在一些问题:

  1. 只有在您的write 方法执行完成后,您才应该将hover 方法绑定到字段。否则,它的工作将不一致,具体取决于创建 table 的速度。

我希望,它会解决你的目的。

【讨论】:

  • @Bojan 很高兴,我可以帮忙。您可以将答案标记为已完成以供其他人参考。
  • @Bojan 我有问题吗?
【解决方案2】:

好吧,为不同的答案道歉,因为这是解决这个问题的完全不同的方式,如下所示,

由于您的主要问题是您的“hoverKartX”jquery 事件未绑定到任何元素,因为您的 html 元素是从 xmlhttp 动态生成的,因此首先您需要确保在生成事件后将其绑定到您的 html 元素,可能你需要重构你的代码并移动你的 $('.hoverKartX').hover()... 和 $('.hoverKartX').mousemove()... 在你的函数 write(arr) 中,因为你已经附加了你的全局上下文中的 mousehover 和 mousemove 事件代码在页面加载时将绑定到任何 html 元素,因为您正在使用 xmlhttp 动态生成这些元素,

然后通过在 mousehover 或 mousemove 事件中使用 jquery 的 attr (如 $(this).attr('user_id') )访问您的自定义 html 属性 user_id 并执行您想做的任何事情...

【讨论】:

  • 我明白这一点,但我只需要我之前描述的方式。
  • 我需要匹配两个id,然后填充html。
  • 您只有一个 id 是从触发 mousehover 事件的元素获得的?所以你需要通过 $('#some_user_id').show(); 来显示 user_id 的信息?
  • 我有一个自定义属性(user_id),它由 JSON“id”填充。在那个 td 元素上,我有相同的类,它在悬停时触发 .hoverKart。现在,当 user_id 与 JSON id 匹配时,我需要从 JSON 中显示有关该特定人的更多信息。
猜你喜欢
  • 1970-01-01
  • 2016-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-31
  • 1970-01-01
  • 1970-01-01
  • 2012-06-11
相关资源
最近更新 更多