作者lonelytea (霸气逼人)
看板Web_Design
标题[问题] javascript class
时间Mon Jun 15 11:24:17 2015
新手问题 (改了点内文)
<script type="text/javascript">
//事件三 随机图片产生
var a;
function myFunction() {
// 乱数
random = Math.floor(Math.random() * 500)
//新增图片
var img = new Image();
img.src = "4.jpg";
a = img.className = "op2";
img.style.width = "50px";
img.style.height = "50px";
// 抓的到className alert(img.className);
alert(a);
//图片出现的位置
document.body.appendChild(img);
img.style.position = "absolute";
img.style.top = 8 + "px";
img.style.left = random + "px";
}
setInterval("myFunction()", 1000);
alert(a);
</script>
我var a定义在广域
但为何只能alert function内的
外面的抓不到值
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 211.75.192.91
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Web_Design/M.1434338660.A.0C8.html
1F:推 NOXI: window.onload / DOMContentLoaded ? 06/15 11:34
※ 编辑: lonelytea (211.75.192.91), 06/15/2015 11:48:45
2F:推 tw0517tw: setInterval第一次执行是马上还是1秒後? 06/15 11:55
3F:推 lonelycoffee: 1秒後 06/15 12:37
4F:推 tooto1985: 因为你1秒後才执行myFunction,但程式并不会停下来等1秒 06/15 14:07
5F:→ tooto1985: 所以这个时候你的a一定是undefined 06/15 14:08
6F:→ tooto1985: 遇到setTimeout,setInterval注意这种会造成非同步执行! 06/15 14:09
7F:→ lonelytea: 那请问我该如何去抓到newimg的left top 06/15 21:59
8F:→ lonelytea: 毕竟无法用class 跟id抓 06/15 22:00
9F:推 s25g5d4: 绑 onload 06/15 22:54
10F:→ lonelytea: 绑了 失败 哈哈哈 06/16 02:05
11F:→ MangoTW: 你到底是LonelyTea还是LonelyCoffee? 06/16 03:15
12F:→ lonelytea: 一个是我的帐号一个是我弟的 有时候没登出就直接用了 06/16 08:20
13F:→ tooto1985: 你需要先执行myFunction()不用setInterval因该就可抓到 06/16 09:02