关于seajs的使用,疑问~~
发布于 10 年前 作者 seasidesun 10231 次浏览 最后一次编辑是 8 年前

是这样的:

<form ...... onsubmit="return check()">
      ....
</form>

<script type="text/javascript">
 function check(){
 	alert("!!!!!!!!!!");
 }
</script>

传统的使用js,上面是没问题的,会弹出提示 “!!!!!!!!!”

但是用了seajs后

define(function (require, exports, module) {
   function check(){
     alert("!!!!!!!!!!");
   }
});

这时候确不能触发check,我哪个地方没遵守规则嘛?

8 回复

新手问题, 对作用域不理解… 第一个定义的 check 是在全局作用域的, 所以从 HTML 属性里能够访问到. 第二个被函数封闭在闭包里面了, 从外面不能调用 跟 SeaJS 半点关系都没有

稍微明白你的意思了~~ 但是我试了一下exports.check = check,还是不能访问

使用addlistener(“click”, function())这种方式?

理论上是这么用的,但还是推荐使用绑定的形式在模块中添加事件。 <pre class=“prettyprint language-html”><code><button onclick=“seajs.use(’./test’, function(test){ test.check(); });”>Check</button></code></pre> <pre class=“prettyprint language-html”><code><script> define(’./test’, function(require, exports, module){ exports.check = function(){ console.log(true); }; }); </script></code></pre>

恩,使用模块,在check .js中写验证逻辑

seajs.use("/scripts/user/check.js");

你的意思是html里不做任何函数的调用,只在check.js这个模块里绑定事件 那绑定事件,可以给表单form绑定一个事件嘛,怎么个绑定法呢

如果这样用的话,算是违背了seajs的初衷。 seajs其中一项作用是减少全局变量。

你只有

window.check = function (){
     alert("!!!!!!!!!!");
   }

才能生效,不过这样跟楼上说的意思大致,建议你仔细浏览一下seajs的官网。

那请教一下,在模块化的思想下,怎么将验证的逻辑放在seajs里,怎么去绑定呢? 给个链接看一下,找了好久都没找到~

做一个简单的例子,目录结构大概是这样的: <pre style=“line-height: 1;”> |- js | |- app | | |- login.js | |- vendor | |- sea.js |- index.html </pre> <h4>index.html</h4> <pre class=“prettyprint language-html”><code><form action=“http://url” method=“post” id=“loginForm”> <input type=“text” name=“user” placeholder=“用户名/邮箱”/> <input type=“text” name=“pass” placeholder=“密码”/> <button id=“submit” type=“submit”>登录</button> </form> <script src=“js/vendor/sea.js”></script> <script> seajs.config({ base: ‘./js/’ }); seajs.use(‘app/login’); </script></code></pre> <h4>app/login.js</h4> <pre class=“prettyprint language-js”><code>define(‘app/login’, function(require, exports, module){ var loginForm = document.getElementById(‘loginForm’); loginForm.onsubmit = function(){ // this is form[id=“loginForm”] if ( this.user.value == ‘’ || this.pass.value == ‘’ ) { alert(‘用户名和密码不能为空’); return false; } else { return true; } }; // 或者可以这么写, var submit = document.getElementById(‘submit’); submit.onclick = function(event){ if ( loginForm.user.value == ‘’ || loginForm.pass.value == ‘’ ) { alert(‘用户名和密码不能为空’); event.preventDefault(); } else { loginForm.submit(); } } });</code></pre>

@saionjisekai 受教了!你写得好清晰,感谢!

回到顶部