Animate ActionScript 3.0按钮超链接异常问题求助
问题分析与解决:Adobe Animate ActionScript按钮跳转异常
哈哈,这个问题我刚学ActionScript的时候也踩过一模一样的坑!咱们先揪出问题的根源:
你给button2和button3绑定事件处理函数的时候,写错了函数名!仔细看你的代码:
button2.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); // 这里应该是mouseDownHandler2 button3.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); // 这里应该是mouseDownHandler3
你把三个按钮都绑定到了第一个mouseDownHandler函数上,不管点哪个按钮,触发的都是跳去website.com的逻辑,自然所有按钮都走同一个链接了。
快速修复方案
只需要把事件绑定的函数名改成对应按钮的处理函数就行,修正后的代码如下:
// 按钮1的事件绑定与处理 button.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); function mouseDownHandler(event:MouseEvent):void { navigateToURL(new URLRequest("https://website.com/")); } // 按钮2的事件绑定与处理(修正函数名) button2.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler2); function mouseDownHandler2(event:MouseEvent):void { navigateToURL(new URLRequest("https://anotherwebsite.com/")); } // 按钮3的事件绑定与处理(修正函数名) button3.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler3); function mouseDownHandler3(event:MouseEvent):void { navigateToURL(new URLRequest("https://yetanotherwebsite.com/")); }
进阶优化方案(更简洁易维护)
其实没必要写三个几乎重复的函数,咱们可以用一个通用处理函数,通过event.target判断点击的是哪个按钮,这样代码更整洁,也不容易再犯类似的错误:
// 给所有按钮绑定同一个通用处理函数 button.addEventListener(MouseEvent.MOUSE_DOWN, handleButtonClick); button2.addEventListener(MouseEvent.MOUSE_DOWN, handleButtonClick); button3.addEventListener(MouseEvent.MOUSE_DOWN, handleButtonClick); // 通用按钮点击处理函数 function handleButtonClick(event:MouseEvent):void { var targetBtn:MovieClip = event.target as MovieClip; var targetURL:String = ""; // 根据按钮实例名匹配对应跳转链接 switch(targetBtn.name) { case "button": targetURL = "https://website.com/"; break; case "button2": targetURL = "https://anotherwebsite.com/"; break; case "button3": targetURL = "https://yetanotherwebsite.com/"; break; } if(targetURL) { navigateToURL(new URLRequest(targetURL)); } }
以后再加新按钮,只需要给按钮绑定这个通用函数,然后在switch里加个case就行,大大减少重复代码,也降低了出错概率。
内容的提问来源于stack exchange,提问作者mbjb
相关产品推荐
相关产品推荐

