原型中漂亮的代码,如何省略'不是函数'空结果选择器上的错误

Beautiful code in prototype, how to omit 'is not a function' errors on empty result selectors

本文关键字:函数 结果 选择器 错误 何省略 漂亮 原型 代码      更新时间:2023-09-26

当我在jQuery中这样做时,li.notsuchelem不存在

$('li.notsuchelem').closest('div')

运行良好

但当我在原型中做同样的事情时,它会给我一个错误

$$('li.notsuchelem').up('div')
>TypeError: $$('li.notsuchelem').up is not a function

我如何从中生成漂亮的代码

if ($$('li.notsuchelem').length) $$('li.notsuchelem').up('div');
>>>>
var tmp;
if ((tmp = $$('li.notsuchelem')).length) tmp.up('div');
>>>>
$$('li.notsuchelem').each(function(el){el.up('div')});

在我看来,一切都和jQuery相反。我能做点什么吗?还是我必须处理它?


嗯,我想我会接受这个答案,但要么我编码错了,要么我就是不喜欢原型

jQuery:

$('.ss_new:not(.force_visible)', wrapper).closest('tr').hide();

原型:

wrapper.select('.ss_new:not(.force_visible)').invoke('up','tr').invoke('hide');

我认为在prototypejs中是这样的。

$$(".test").invoke("up", "div");

您可以将返回的数组强制转换为数字,而不是长度。此外,您还可以使用逻辑AND(&&)运算符的副作用。

+$$('li.notsuchelem') && $$('li.notsuchelem').up('div');