避免jQuery静默的模式失败 [英] Patterns for avoiding jQuery silent fails

查看:92
本文介绍了避免jQuery静默的模式失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么好的做法可以避免你的jQuery代码无声地失败?

Is there any good practice to avoid your jQuery code silently fail?

例如:

$('.this #is:my(complexSelector)').doSomething();

我知道每次执行此行时,选择器都要匹配至少一个元素,或一定数量的元素。有没有任何标准或好的方法来验证?

I know that every time this line get executed, the selector is intended to match at least one element, or certain amount of elements. Is there any standard or good way to validate that?

我想过这样的事情:

var $matchedElements = $('.this #is:my(complexSelector)');
if ($matchedElements.length < 1)
    throw 'No matched elements';
$matchedElements.doSomething();

此外,我认为单元测试将是一个有效的选项,而不是弄乱代码。

Also I think unit testing would be a valid option instead of messing the code.

我的问题可能很愚蠢,但我想知道是否有比我目前正在做的事情更好的选择。此外,也许我错误的方式检查是否有任何元素匹配我的选择器。但是,随着页面的不断增长,选择器可能会停止匹配某些元素,而功能部分可能会无意中停止工作。

My question may be silly, but I wonder whether there is a better option than the things that I'm currently doing or not. Also, maybe I'm in the wrong way checking if any element match my selector. However, as the page continues growing, the selectors could stop matching some elements and pieces of functionality could stop working inadvertently.

推荐答案

你可以写一个插件:

jQuery.fn.requireElements = function (amount, exactMatch) {
    if (amount === undefined) {
        amount = 1;
    };

    if (this.length < amount || this.length > amount && exactMatch) {
        throw new Error(this.length " elements instead of " (exactMatch ? "at least " : "") + amount);
    };

    return this;
};

然后:

$('yourSelector').requireElements(2).bind('click', function () {

});

这篇关于避免jQuery静默的模式失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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