[英]Passing object as parameter in Javascript
I got this 我懂了
for(m in _data.data)
{
var _person= new Person(_data.data[m].Properties); //return a person object
$('ul.v_list').append("<li>"+_person.person_name+'</li>').css("cursor", "pointer");
$('ul.v_list').find('li:last').bind('click', function(){onPersonChanged(_person)});
}
And this another function 而这另一个功能
function onPersonChanged(person){
alert("You have clicked " + person.person_name);
};
Everytime is passing the last object created in the Person Object to the onPersonChanged
function so it alerts the last name in the list if I click in the first li
or another li
element nested in the ul
. 每次都将Person对象中创建的最后一个对象传递给onPersonChanged
函数,因此如果我单击第一个li
或嵌套在ul
中的另一个li
元素,它会警告列表中的姓氏。 eg.: 例如。:
<ul class='v_list'>
<li>James</li>
<li>Paul</li>
<li>Bonnie</l>
</ul>
When I do a click in Paul I expect an alert showing "You have clicked Paul" instead I always get the last one li in the list: "You have clicked Bonnie". 当我在保罗点击时,我希望显示“你已点击保罗”的提示,而我总是在列表中找到最后一个:“你点击了Bonnie”。 How can I get the correct alert for the selected li
? 如何获得所选li
的正确警报?
Your onPersonChanged
function is being called after the loop has been executed therefore only the last _person
in the loop will be passed through. 在循环执行后调用onPersonChanged
函数,因此只传递循环中的最后一个_person
。 Look up "closures" in javascript. 在javascript中查找“闭包”。
To fix it you should do the following: 要修复它,您应该执行以下操作:
for(m in _data.data)
{
var _person= new Person(_data.data[m].Properties);
(function(p) {
$('ul.v_list').append("<li>"+p.person_name+'</li>').css("cursor", "pointer");
$('ul.v_list').find('li:last').bind('click', function(){onPersonChanged(p)});
})(_person);
}
this will evaluate the current value of _person
as it is at that point in the loop as opposed to evaluating it after the loop has finished. 这将评估_person
的当前值,因为它在循环中的那一点,而不是在循环结束后评估它。
The (function(p) { ... })(_person);
(function(p) { ... })(_person);
is an anonymous self-executing function. 是一个匿名的自执行功能。 this creates a new sub-scope in your for loop which will preserve the value of _person correctly. 这会在for循环中创建一个新的子范围,这将正确保留_person的值。
You want to create a closure for the current value of _person
. 您想为_person
的当前值创建一个闭包。 But you need a function that will be immediately evaluated for that. 但是你需要一个能够立即对其进行评估的函数。
Your function in the bind statement is only evaluated when the click event occurs. 只有在发生click事件时才会评估bind语句中的函数。
@Darko Z's code is a good example of how to fix. @Darko Z的代码是如何修复的一个很好的例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.