jQuery 如何使用从点击中获取的 ID div

jQuery How to use a ID grabbed from a clicked div

我正在构建的网站上有一个人员部分,该部分使用同位素进行过滤。当我点击一个人时,我想在右侧显示他们的完整信息。单击发生时,我获取 id 并将其存储为变量。然后我将变量命名为与抓取的 ID 相匹配。

如何使用抓取的ID来定位我的js文件中存储的变量?目前它只打印出从点击的 div.

抓取的 ID
var userOne = "<p>userOne info<p>";
var userTwo = "<p>userTwo info<p>";
var userThree = "<p>userThree info<p>";    

$('.item').on("click", function(){
var id = $(this).attr('id'); // this grabs the ID of the div eg userOne
var printId = id; //trying to change the variable so I can use it
$('.bio').html(printID); //this is where it should print out
});

你不能像那样访问变量名,相反你可以做的是使用动态键

访问对象的属性

假设变量userOne/userTwo在全局范围内,你可以使用括号表示法

var userOne = "<p>userOne info<p>";
var userTwo = "<p>userTwo info<p>";
var userThree = "<p>userThree info<p>";

$('.item').on("click", function () {
    var printId = window[this.id];
    $('.bio').html(printID);
});

另一种选择是将这些值存储为对象的属性

var user = {
    userOne: "<p>userOne info<p>",
    userTwo: "<p>userTwo info<p>",
    userThree: "<p>userThree info<p>"
};

$('.item').on("click", function () {
    var printId = user[this.id];
    $('.bio').html(printID);
});

尝试

html

<div class="item" data-user="<p>userOne info<p>"></div>

js

$(".item").on("click", function(e) {
  $(".bio").html($(this).data("user"))
})

$(".item").on("click", function(e) {
  $(".bio").html($(this).data("user"))
})
div:not(.bio) {
  border:1px dotted grey;
  width: 24px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="item" data-user="<p>userOne info<p>">1</div><br />
<div class="item" data-user="<p>userTwo info<p>">2</div><br />
<div class="item" data-user="<p>userThree info<p>">3</div><br />
<div class="bio"></div>