使用requirejs调用一个函数 [英] call a function using requirejs

查看:140
本文介绍了使用requirejs调用一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用requirejs调用一个函数?



这是一个非常简单的问题,但令人惊讶的是,目前还没有任何教程或示例能够帮助我。 / p>

这是我的html文件中的代码。

  ... 
< script src =stuff.js>< / script>
< button onclick =doStuff(4,2);> DoStuff< / button>
...

这是我要求的js。

  define([jquery],function($){
函数doStuff(a,b){
//做一些东西
}
});

为什么这不起作用?我得到
ReferenceError:doStuff未定义

解决方案

我通过传递函数来设法找到问题的解决方案进入html代码。这不是很优雅,但它的工作原理。



index.html

 < button onclick =doSomeStuff(4,2);> DoStuff< / button> 
< script>
require(['stuff.min'],function(myStuff){
function doSomeStuff(a,b){
myStuff.doStuff(a,b);
}
});
< / script>

stuff.js

  define([jquery],function($){
函数doStuff(a,b){
//做一些东西
}
return {doStuff:doStuff};
});


How do I call a function using requirejs?

It's an overly simple question, but surprisingly enough no tutorial or example has been able to help me so far.

This is the code in my html file.

...
<script src = "stuff.js"></script>
<button onclick="doStuff(4, 2)";>DoStuff</button>
...

This is my require js.

define(["jquery"], function ($) {
  function doStuff(a, b) {
    //does some stuff
  }
});

Why does this not work? I get ReferenceError: doStuff is not defined

解决方案

I managed to find a solution for the question by passing the function into the html code. It's not very elegant, but it works.

index.html

<button onclick = "doSomeStuff(4,2);">DoStuff</button>
<script>
  require(['stuff.min'], function(myStuff){
    function doSomeStuff(a,b) {
      myStuff.doStuff(a,b);
    }
  });
</script>

stuff.js

define(["jquery"], function ($) {
  function doStuff(a,b) {
    //does some stuff
  }
  return {doStuff:doStuff};
});

这篇关于使用requirejs调用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆