外部的js 方法如何能调用egret内部的方法

JavaScript08

外部的js 方法如何能调用egret内部的方法,第1张

ts 调用 js

步骤

找到 js 调用 js 的方法。

增加方法调用的声明。 请参考 如何生成 .d.ts 。

示例

js 内的方法

function callJsFunc(msg) {    console.log("msg from egret : " + msg)}

ts 内声明

declare function callJsFunc(msg:string)//可以放在 ts 文件内(建议在顶部或者底部,中间的没试过)或者单独放到一个 .d.ts 文件中,请不要放在其他类型的文件内。msg 类型根据函数体判断。

ts 内调用

callJsFunc("hello js")

输出

msg from egret : hello js

总结:在 js 调用 js 的基础上增加声明。其他的比如变量等,也是按上面步骤来实现。

js 调用 ts

js 调用 ts 其实就是 ts 调用 ts,由于 ts 调用 ts 可能会有同模块下的省略写法,因此只要使用不同模块下的调用来写即可。

步骤

找到非同一模块下 ts 的调用(比如 example.A.CallEgretFunc("hello"))。

完全按上面调用的方式来写 (比如上面的 example.A.CallEgretFunc("hello"))。

示例

ts 内的方法

module exampleA {    export class A {        public callEgretMethod(msg:string):void {            console.log("method msg from js : " + msg)       }        public static CallEgretFunc(msg:string):void {            console.log("static msg from js : " + msg)       }    }}

非同一模块下 ts 调用

module exampleB {    export function b() {        //调用方法        var a:exampleA.A = new exampleA.A()       a.callEgretMethod("method")       //调用静态函数        exampleA.A.CallEgretFunc("function")   }}

js 内调用

var a = new exampleA.A()//去掉 a 的类型a.callEgretMethod("method")exampleA.A.CallEgretFunc("function")

输出

method msg from js : methodstatic msg from js : function

引入对应的js文件,然后直接调用其方法名。如:

index.js

function aa(){

    alert("Hello World!")

}

在index.html文件中:

<script src="index.js"></script>

<script>

    window.onload = function(){

        aa()    //调用

    }

</script>

src是js文件的路径及名称,根据js文件位置写。

Js文件中调用其它Js函数的方法:

1、例如有这样一个html,里面有一个按钮,当按下时调用b.js文件中的方法b()。而b()中又要调用a.js文件中的方法a()。那我们应该怎么做呢?

首先,在html中引入b.js,并在</body>之后加入引用语句。必须注意,将要引入的Js文件代码放在</body>下面。

<html>

<body>

<input type="button" value="ok" onclick="javascript:b()">

</body>

<!--这里引用要放在body下面-->

<script language="JAVASCRIPT" src='b.js'></script>

</html>

b.js文件中引入a.js,内容如下:

new_element=document.createElement("script")

new_element.setAttribute("type","text/javascript")

new_element.setAttribute("src","a.js")// 在这里引入了a.js

document.body.appendChild(new_element)

function b() {

a()

}

在b.js文件中前4行代码中我们引入了a.js文件,并在第7行代码中调用了a.js代码中的a()方法。

注意:<script language="JAVASCRIPT" src='b.js'></script>一定要放在body下面。

因为在b.js中用到了body(document.body.appendChild(new_element))

如果将引如b.js的代码放在body上面,也就是说, 进入页面后,还没有生成body就已经执行b.js里的document.body.appendChild(new_element)了。 这时body不存在就会抛javascript错误。