• Make jQuery throw error when it doesn't match an element


    Make jQuery throw error when it doesn't match an element

    解答1

    You could make a plugin to use to ensure that the jQuery object is not empty:

    $.fn.ensure = function() {
      if (this.length === 0) throw "Empty jQuery result."
      return this;
    }

    Usage:

    $('ul.some-list').ensure().append(listItem);

    解答2

    In my case, I wanted it automatically applied to everything, so I modified the jQuery constructor. I suggest you only use this during development to catch mistakes, but keep it out of your production so as not to confuse others. As it's not an error, I've just used console logging. However I've added a commented out throw in case you would rather use that:

    var jQueryInit = $.fn.init;
    
    $.fn.init = function(arg1, arg2, rootjQuery) {
        var element = new jQueryInit(arg1, arg2, rootjQuery);
        if (arg1 && element.length === 0) {
            console.log(arg1 +" doesn't exist");
            // throw arg1 +" doesn't exist"
        }
        return element;
    };

    I really wish there was an option in jQuery for turning this on during dev.

    In case anybody is wondering... having the selector return a result set, when there are no valid matches, is a deliberate decision by the developers of jQuery. It means you can apply some code to a collection of elements, even if there is a possibility of there being none. A good example is comments on a page, or checked checkboxes. If it threw an error when there were no were elements found, then you would have to add checks for existence to your code. The following topic has more info: https://stackoverflow.com/a/3709823/109561

    This is great feature for keeping production code lean. However it can really bite you in the ass while developing if you make a small typo; or if you try selecting an ID named "foobar" when you should be selecting a class called "foobar".

  • 相关阅读:
    Centos7 KVM启用嵌套虚拟化
    CentOS 桥接网卡配置
    centos iso镜像自动挂载
    git status没有颜色提示
    virt-install 安装系统和启动虚机
    Python 源代码代码打包成 whl 文件
    存储池与存储卷,使用virt-install创建虚拟机
    ftp 搭建 centos 源
    git 生成并添加 SSH key
    linked-list-cycle leetcode C++
  • 原文地址:https://www.cnblogs.com/chucklu/p/11131024.html
Copyright © 2020-2023  润新知