我正在尝试做的是基于通过 AJAX 获得的数据,我正在将页面上的某些元素更改为不同的。一个简化的版本是这样的:
例子:
HTML:
<ul id="friends">
<li id="1-1" onclick="dont_alert()"> Andy </li>
<li id="1-2" onclick="dont_alert()"> Paul </li>
<li id="1-3" onclick="dont_alert()"> Saul </li>
<li id="1-4" onclick="dont_alert()"> Rita </li>
<li id="1-5" onclick="dont_alert()"> Greg </li>
</ul>
<input type="button" onclick='callback()' value="Go!" />
相关 JS:函数 alert_this(value) { alert(value); }
function dont_alert() {
alert('...');
}
function callback() {
var data_received = [["1","1","Andy"], ["1","5","Greg"]];
for (friend in data_received) {
if (data_received[friend][0] == undefined) continue;
var friend_id = '#'+ data_received[friend][0] +'-'+ data_received[friend][1];
$(friend_id).attr('onclick', '');
$(friend_id).css('background', 'red');
$(friend_id).click(function () {
alert_this(data_received[friend][2]);
});
}
}
这样做的结果是两个元素都 alert 'Greg' 而不是适当的值。
任何对答案的刺激将不胜感激!:D