If you click any of the id's in the list you added in jQuery, the last value will be output.

Asked 1 years ago, Updated 1 years ago, 37 views

I created the following program in jQuery.
A program that alerts you to the name of the div number you pressed when you click div for each "#no"+ number.

<!DOCTYPE html>
<html lang="ja">
<head>
<metacharset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Click Test</title>
<link rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css
/bootstrap.min.css">
</head>
<body>

<ul class="list-group" id="oomoto">
</ul>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script
pt>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></sc
US>script>
<script>
vardata=
{
   "1535525652": {"name": "Honara"},
   "1535508625": {"name": "here"}
}
for (vari in data) {
varh='<liid="li'+i+'" class="list-group-item list-group-item-info">'
       +'<div id='no'+i+'>'+data[i].name+'</div>';
       + '</li>';
      $('#oomoto').append(h);
$(document).on('click', "#no" + i, function(){
  alert($('#no'+i).text());
});
}
</script>
</body>
</html>

However, it doesn't move as expected.
(1) Since it's JSON, the order doesn't matter, but the display is in the order of "Konyakura" and "Honyara."
(2) "Whether you click ""Konyakura"" or ""Honyakara"", both alerts appear ""Honyakara""

"

What I really want to solve is (2), but it seems to correlate with (1).
If you know how to solve this problem, I would appreciate it if you could tell me one of the above questions.

jquery

2022-09-29 22:07

1 Answers

closure:

function(){
  alert($('#no'+i).text());
}

This is because the variable i has been captured in .(1)is not directly related to .

When referring to variables defined outside the JavaScript closure, the variables themselves are tied to the closure, not the value of the variable when the closure was created.This results in the use of the latest i value when the closure runs (in this example, {"name":"Honyara"} key "1535525652").

For the time being, in your case, using this seems to solve this problem.

Please look at the corresponding part like this.

$(document).on('click', "#no" + i, function(){
    alert($(this).text());
});


2022-09-29 22:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.