定位动态 Div

Targeting Dynamic Div

我在单击时无法定位特定的 div,目前当我单击“currentTarget.id”时,函数 returns 我的所有 div 对象JSON 文件而不是单击的文件。

我尝试了很多不同的解决方案,从针对后端 heroku 服务器到针对客户端本地,但每次尝试都“几乎已解决”/90% 的方式,但从未完全解决。

我认为问题发生在尝试将动态 JSON 值映射到用户卡片时,它与“currentTarget.id”代码冲突?

因为当我删除 map/reduce 函数时,我可以在 dividually 中定位 divs 但没有“地图”和“return”代码我是无法显示我需要的所有必需数据。

感谢您抽出宝贵时间,我们将不胜感激。

最好的, 史蒂夫

//THIS IS THE CODE TO CREATE DYNAMIC CLASSES FOR INDUSTRY VALUES
const industry_class = {
    "Health": "health-badge",
    "Education": "education-badge",
    "Construction": "construction-badge",
    "Science": "science-badge"
};

//THIS IS THE CODE TO REFERENCE EXTERNAL JSON FILE
var userJSON = 'https://mighty-oasis-08666.herokuapp.com/users'

//THIS IS THE CODE TO FETCH EXTERNAL JSON FILE
$.getJSON(userJSON, function(populateUsers) {

//THIS IS THE CODE TO POPULATE JSON DATA INTO TEMPLATE LITERAL CARD
var userCard = populateUsers.map(({id, industry}) => {
    let cls = industry_class[industry.trim()] || "";
    return `
            <div class='col col-4 align-items-stretch user-container'>
                <div id="${id}" class="card user-card">
                    <div class="card-body">
                        <h6 class="industry-type title ${cls}">${industry}</h6>
                    </div>
                </div>
            </div>`;
    }).join("");
    $('#user-grid').append(userCard)
    //THIS IS THE CODE TO APPLY DYNAMIC CLASSES TO INDUSTRY VALUES
    $userType.each(function() {
        var $this = jQuery(this);
        let industry = $this.text().trim();
        if (industry in industry_class) {
            $this.addClass(industry_class[industry]);
        }
    });
});



//THIS IS THE CODE TO RUN WHEN USER CARD IS CLICKED
$("#user-grid").on("click", ".user-card", function (e) {

        //THIS IS THE CODE TO CREATE DYNAMIC CLASSES FOR INDUSTRY VALUES
        const industry_class = {
            "Health": "health-badge",
            "Education": "education-badge",
            "Construction": "construction-badge",
            "Science": "science-badge"
        };

        //THIS IS THE CODE TO REFERENCE EXTERNAL JSON FILE
        var userJSON = 'https://mighty-oasis-08666.herokuapp.com/users'

        //THIS IS THE CODE TO FETCH EXTERNAL JSON FILE
        $.getJSON(userJSON, function(populateUsers) {
            //THIS IS THE CODE TO TARGET SPECIFIC JSON OBJECT ID VALUE
            const selectedUserId = e.currentTarget.id;
            const selectedUserData = populateUsers.find(
            (user) => user.id === Number(selectedUserId));

        //THIS IS THE CODE TO POPULATE JSON DATA INTO TEMPLATE LITERAL MODAL CARD
        var userModal = populateUsers.map(({id, industry}) => {
            let cls = industry_class[industry.trim()] || "";
            return `
            <div class='col col-4 align-items-stretch user-container'>
                <div id="${id}" class="card user-card">
                    <div class="card-body">
                        <h6 class="industry-type title ${cls}">${industry}</h6>
                    </div>
                </div>
            </div>
        `;
        }).join("");
        //THIS IS THE CODE TO APPEND DIV TO MODAL
        $("#modal-content").append(userModal);
        //THIS IS THE CODE TO APPLY DYNAMIC CLASSES TO INDUSTRY VALUES
        $userType.each(function() {
            var $this = jQuery(this);
            let industry = $this.text().trim();
            if (industry in industry_class) {
                $this.addClass(industry_class[industry]);
            }
        });
    });
    $("#user-modal").modal({ show: true });
});

//THIS IS THE CODE TO CLEAR ALL THE JSON DATA WHEN MODAL IS CLOSED
$("#user-modal").on("hidden.bs.modal", function(){
    $("#modal-content").html("");
});
.health-badge {
    background-color: purple;
    color: green;
    height: 80px;
    width: 80px;
}
.science-badge {
    background-color: black;
    color: yellow;
    height: 80px;
    width: 80px;
}
.construction-badge {
    background-color: blue;
    color: white;
    height: 80px;
    width: 80px;
}
.education-badge {
    background-color: orangered;
    color: black;
    height: 80px;
    width: 80px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<!-- Modal -->
<div id="user-modal" class="user-modal modal fade" tabindex="-1" role="dialog" aria-labelledby="hybrid-strain-chronic" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div id="modal-content">

        </div>
    </div>
</div>


<!-- User Grid -->
<div id="user-grid" class="row container fluid-container"></div>

您可以使用 .filter 过滤来自服务器的 return 数据,并且只获取 JSON 数组 其中值 id 是一样的。此外,id 是唯一的,所以我们只需要获取一条记录,这就是为什么不需要使用 .each 循环,只需使用 values[0] 访问记录,然后在过滤后使用此内容数据访问所有字段。

演示代码 :

const industry_class = {
  "Health": "health-badge",
  "Education": "education-badge",
  "Construction": "construction-badge",
  "Science": "science-badge"
};
var userJSON = 'https://mighty-oasis-08666.herokuapp.com/users'
$.getJSON(userJSON, function(populateUsers) {
  var userCard = populateUsers.map(({
    id,
    industry
  }) => {
    let cls = industry_class[industry.trim()] || "";
    return `
            <div class='col col-4 align-items-stretch user-container'>
                <div id="${id}" class="card user-card">
                    <div class="card-body">
                        <h6 class="industry-type title ${cls}">${industry}</h6>
                    </div>
                </div>
            </div>`;
  }).join("");
  $('#user-grid').append(userCard)
});


$("#user-grid").on("click", ".user-card", function(e) {
  var userJSON = 'https://mighty-oasis-08666.herokuapp.com/users'
  const selectedUserId = parseInt($(this).attr('id'));
  $.getJSON(userJSON, function(populateUsers) {
  //get only json where id matches
    var values = $(populateUsers)
      .filter(function(i, n) {
        return n.id === selectedUserId;
      });
    let cls = industry_class[values[0].industry.trim()] || "";
    //gte all dataas..
    $("#modal-content").append(`<div class='user-container'><div class="${cls}"><h6 class="industry-type title">${values[0].industry}</h6> <h5>${values[0].name}</h5> <h5>${values[0].username}</h5></div></div></div>`);
    $("#user-modal").modal({
      show: true
    });
  });
});
$("#user-modal").on("hidden.bs.modal", function() {
  $("#modal-content").html("");
});
.health-badge {
  background-color: purple;
  color: green;
  height: 80px;
  width: 80px;
}

.science-badge {
  background-color: black;
  color: yellow;
  height: 80px;
  width: 80px;
}

.construction-badge {
  background-color: blue;
  color: white;
  height: 80px;
  width: 80px;
}

.education-badge {
  background-color: orangered;
  color: black;
  height: 80px;
  width: 80px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<!-- Modal -->
<div id="user-modal" class="user-modal modal fade" tabindex="-1" role="dialog" aria-labelledby="hybrid-strain-chronic" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div id="modal-content">

    </div>
  </div>
</div>


<!-- User Grid -->
<div id="user-grid" class="row container fluid-container"></div>