用实际代码解释我的问题可能更容易。
<script type='text/javascript' src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type='text/javascript'>
var username_array = [];
var text_array = [];
var virtual_name;
$(document).ready(function(){
document.body.style.backgroundColor= "rgb(0, 188, 237)";
var name = prompt("Please enter your name.");
if(name!=null){
x = "Hello " + name + "!";
a = document.createElement("p");
a.innerHTML=x;
document.body.appendChild(a);
b = document.createElement("p");
b.addEventListener('click',question,false);
b.style.cursor='pointer';
b.style.textDecoration="underline";
b.innerHTML="Check out what you look like on Twitter."
document.body.appendChild(b);
}
function question () {
$.ajax({
url: 'http://search.twitter.com/search.json?q='+name+'&callback=?&rpp=5',
type: 'GET',
dataType: 'json',
success: function (data){
for(i=0;i<data.results.length;i++) {
pic = data.results[i].profile_image_url;
var img = document.createElement("img");
img.setAttribute("id", "profile"+i);
img.src=pic;
img.width=50;
img.height=50;
img.addEventListener('click', realname, false);
img.style.cursor='pointer';
document.body.appendChild(img);
username = data.results[i].from_user_name;
username_array.push(username);
text = data.results[i].text;
text_array.push(text);
sequence = i;
}
check_array();
}
})
c = document.createElement("p");
c.innerHTML="Which one is you?"
document.body.appendChild(c);
}
});
function check_array() {
}
var sequence;
function realname() {
i=Math.floor(Math.random()*5);
d = document.createElement("p");
d.innerHTML="Here is your virtual name: " + username_array[i];
document.body.appendChild(d);
e = document.createElement("p");
e.innerHTML= username_array[i] +" actually has something to say to you:";
e.style.textDecoration="underline";
e.addEventListener('click',say,false);
e.style.cursor="pointer";
document.body.appendChild(e);
sequence = i;
}
</script>
我遇到的问题是这一行:
function realname() {
i=Math.floor(Math.random()*5);
...}
和
img.addEventListener('click', realname, false);
理想情况下,我希望用户单击 img,我可以获取它的索引值并将其传递给 realname 函数,这样我就可以从 data.result 中获取与配置文件图像匹配的正确用户名。现在,我在函数 realname 中生成的随机“i”只是为了让某些东西出现而伪造的。
我不确定我是否解释得足够清楚。谢谢任何人都可以提供帮助。