循环运行时,如何强制Jquery/JS替换变量


<html>
<header><script src = "/jquery.js"></script></header>
<div id="cars"></div>
<script>
$.post({
url:"/cars.php",
dataType:"JSON",
success:function(cars){
var fromidcount = Object.keys(cars).length;
for (var i=0;i<=(fromidcount-1);i++){
var carname= Object.keys(cars)[i];
$("#cars").append("<input type='button' id='"+carname+"'>");
$("#"+carname).click(function(){
alert("selected "+carname);
});
}
}
});
</script>
</html>

我从PHP获得了一个JSON数组,并使用其中的值通过Jquery动态创建HTML按钮。到目前为止,它制造了两个ID为"宝马"one_answers"丰田"的按钮。然后,我的脚本应该创建指令,这样当单击id="BMW"时,它就会提醒"Selected BMW"。当id="Toyota"被点击时,它应该提醒"Selected Toyota.

然而,当我点击按钮时,两者都会提醒"选定的丰田"。我已经检查了开发工具,并确认按钮ID是宝马和丰田,但每个按钮的事件仍然显示alert("selected "+carname);,而不是alert("selected "+"BMW");alert("selected "+"Toyota");

因此,我认为发生的事情是,当单击按钮时,Jquery才会更新alert("selected "+carname);中的"carname"变量。但到那时,循环已经结束,所以它获取的值是循环的最后一个值,那就是丰田。

您可以看到,我在for循环中有多个变量carname的实例。除alert("selected "+carname);中的值外,所有carname实例都被它们各自的值替换。为什么会这样,我该如何修复?

汽车是一个多维的阵列。[[bmw],[丰田]]

您在这里遇到了JavaScript的闭包/词法范围规则。您需要有另一个函数来关闭carname变量,在该变量中添加事件处理程序,但从ID中读取汽车名称可能更容易,因为您有它:

$("#"+carname).click(function(){
alert("selected " + this.id);
});

如果您需要将ID用于其他事情,也可以将汽车名称添加为data-属性。

必须使用$(this).attr("id")才能获得Carname

$.post({
url:"/cars.php",
dataType:"JSON",
success:function(cars){
var fromidcount = Object.keys(cars).length;
for (var i=0;i<=(fromidcount-1);i++){
var carname= Object.keys(cars)[i];
$("#cars").append("<input type='button' id='"+carname+"'>");
$("#"+carname).click(function(){
alert("selected "+$(this).attr("id"));
});
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<header><script src = "/jquery.js"></script></header>
<div id="cars"></div>
</html>

您可以在函数中定义用于单击的处理程序。

new userService().getUsers().then(users => {
users.forEach(user => {
const inputElement = document.createElement('input');
inputElement.value = user.name;
inputElement.type = 'button';
inputElement.addEventListener('click', () => alert(user.name));
document.body.appendChild(inputElement);
});
});
function userService() {
const users = [{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
{
"id": 3,
"name": "Clementine Bauch",
"username": "Samantha",
"email": "Nathan@yesenia.net",
"address": {
"street": "Douglas Extension",
"suite": "Suite 847",
"city": "McKenziehaven",
"zipcode": "59590-4157",
"geo": {
"lat": "-68.6102",
"lng": "-47.0653"
}
},
"phone": "1-463-123-4447",
"website": "ramiro.info",
"company": {
"name": "Romaguera-Jacobson",
"catchPhrase": "Face to face bifurcated interface",
"bs": "e-enable strategic applications"
}
},
{
"id": 4,
"name": "Patricia Lebsack",
"username": "Karianne",
"email": "Julianne.OConner@kory.org",
"address": {
"street": "Hoeger Mall",
"suite": "Apt. 692",
"city": "South Elvis",
"zipcode": "53919-4257",
"geo": {
"lat": "29.4572",
"lng": "-164.2990"
}
},
"phone": "493-170-9623 x156",
"website": "kale.biz",
"company": {
"name": "Robel-Corkery",
"catchPhrase": "Multi-tiered zero tolerance productivity",
"bs": "transition cutting-edge web services"
}
},
{
"id": 5,
"name": "Chelsey Dietrich",
"username": "Kamren",
"email": "Lucio_Hettinger@annie.ca",
"address": {
"street": "Skiles Walks",
"suite": "Suite 351",
"city": "Roscoeview",
"zipcode": "33263",
"geo": {
"lat": "-31.8129",
"lng": "62.5342"
}
},
"phone": "(254)954-1289",
"website": "demarco.info",
"company": {
"name": "Keebler LLC",
"catchPhrase": "User-centric fault-tolerant solution",
"bs": "revolutionize end-to-end systems"
}
},
{
"id": 6,
"name": "Mrs. Dennis Schulist",
"username": "Leopoldo_Corkery",
"email": "Karley_Dach@jasper.info",
"address": {
"street": "Norberto Crossing",
"suite": "Apt. 950",
"city": "South Christy",
"zipcode": "23505-1337",
"geo": {
"lat": "-71.4197",
"lng": "71.7478"
}
},
"phone": "1-477-935-8478 x6430",
"website": "ola.org",
"company": {
"name": "Considine-Lockman",
"catchPhrase": "Synchronised bottom-line interface",
"bs": "e-enable innovative applications"
}
},
{
"id": 7,
"name": "Kurtis Weissnat",
"username": "Elwyn.Skiles",
"email": "Telly.Hoeger@billy.biz",
"address": {
"street": "Rex Trail",
"suite": "Suite 280",
"city": "Howemouth",
"zipcode": "58804-1099",
"geo": {
"lat": "24.8918",
"lng": "21.8984"
}
},
"phone": "210.067.6132",
"website": "elvis.io",
"company": {
"name": "Johns Group",
"catchPhrase": "Configurable multimedia task-force",
"bs": "generate enterprise e-tailers"
}
},
{
"id": 8,
"name": "Nicholas Runolfsdottir V",
"username": "Maxime_Nienow",
"email": "Sherwood@rosamond.me",
"address": {
"street": "Ellsworth Summit",
"suite": "Suite 729",
"city": "Aliyaview",
"zipcode": "45169",
"geo": {
"lat": "-14.3990",
"lng": "-120.7677"
}
},
"phone": "586.493.6943 x140",
"website": "jacynthe.com",
"company": {
"name": "Abernathy Group",
"catchPhrase": "Implemented secondary concept",
"bs": "e-enable extensible e-tailers"
}
},
{
"id": 9,
"name": "Glenna Reichert",
"username": "Delphine",
"email": "Chaim_McDermott@dana.io",
"address": {
"street": "Dayna Park",
"suite": "Suite 449",
"city": "Bartholomebury",
"zipcode": "76495-3109",
"geo": {
"lat": "24.6463",
"lng": "-168.8889"
}
},
"phone": "(775)976-6794 x41206",
"website": "conrad.com",
"company": {
"name": "Yost and Sons",
"catchPhrase": "Switchable contextually-based project",
"bs": "aggregate real-time technologies"
}
},
{
"id": 10,
"name": "Clementina DuBuque",
"username": "Moriah.Stanton",
"email": "Rey.Padberg@karina.biz",
"address": {
"street": "Kattie Turnpike",
"suite": "Suite 198",
"city": "Lebsackbury",
"zipcode": "31428-2261",
"geo": {
"lat": "-38.2386",
"lng": "57.2232"
}
},
"phone": "024-648-3804",
"website": "ambrose.net",
"company": {
"name": "Hoeger LLC",
"catchPhrase": "Centralized empowering task-force",
"bs": "target end-to-end models"
}
}
];
this.getUsers = () => Promise.resolve(users);
}
body {
display: flex;
flex-direction: column;
}
input[type="button"] {
margin: 0.2rem;
}

最新更新