有没有相当于Ruby的Javascript和?
发布时间:2020-12-17 03:33:26 所属栏目:百科 来源:网络整理
导读:在尝试使我的 Javascript不引人注目时,我正在使用onLoads向 input等添加功能.使用Dojo,这看起来像: var coolInput = dojo.byId('cool_input');if(coolInput) { dojo.addOnLoad(function() { coolInput.onkeyup = function() { ... }; });} 或者,大致相当于
在尝试使我的
Javascript不引人注目时,我正在使用onLoads向< input>等添加功能.使用Dojo,这看起来像:
var coolInput = dojo.byId('cool_input'); if(coolInput) { dojo.addOnLoad(function() { coolInput.onkeyup = function() { ... }; }); } 或者,大致相当于: dojo.addOnLoad(function() { dojo.forEach(dojo.query('#cool_input'),function(elt) { elt.onkeyup = function() { ... }; }); }); 有没有人写过Ruby的andand的实现,这样我才能做到以下几点? dojo.addOnLoad(function() { // the input's onkeyup is set iff the input exists dojo.byId('cool_input').andand().onkeyup = function() { ... }; }); 要么 dojo.byId('cool_input').andand(function(elt) { // this function gets called with elt = the input iff it exists dojo.addOnLoad(function() { elt.onkeyup = function() { ... }; }); }); 解决方法
您想要的确切语法在JavaScript中是不可能的. JavaScript执行的方式需要以非常基本的方式进行更改.例如:
var name = getUserById(id).andand().name; // ^ // |------------------------------- // if getUserById returns null,execution MUST stop here | // otherwise,you'll get a "null is not an object" exception 但是,JavaScript不能以这种方式工作.它根本没有. 以下行几乎完全按照您的要求执行. var name = (var user = getUserById(id)) ? user.name : null; 但是可读性不会扩展到更大的例子.例如: // this is what you want to see var initial = getUserById(id).andand().name.andand()[0]; // this is the best that JavaScript can do var initial = (var name = (var user = getUserById(id)) ? user.name : null) ? name[0] : null; 并且存在这些不必要变量的副作用.我使用这些变量来避免双重查找.变量正在弄乱上下文,如果这是一个大问题,你可以使用匿名函数: var name = (function() {return (var user = getUserById(id)) ? user.name : null;})(); 现在,用户变量被正确清理,每个人都很高兴.但是哇!什么打字! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |