How to catch when a selector is passed to jQuery() that does not exist in document, to stop further possible errors or omissions?

佐手、 提交于 2019-12-24 06:44:30

问题


Given

$(function() {
  $(".planChoice").on("click", function() {
    console.log(123)
  });
  
  console.log($(".planChoice").length)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

jQuery happilly allows chaining .on() to jQuery() call where selector passed to jQuery() does not exist in document. Where .addEventListener() throws a TypeError

Cannot read property 'addEventListenet' of null

$(function() {
  document.querySelector(".planChoice")
  .addEventListener("click", function() {
    console.log(123)
  });
  
  console.log(document.querySelector(".planChoice").length)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

How can we adjust (improve) jQuery() to throw the same TypeError when the selector or element does not exist in document at the time jQuery() is called and, or a jQuery method is chained to the jQuery() call which returns a jQuery object - though no underlying element exists matching the selector string within document at the time of the call?


回答1:


If you really want to throw an error, you can edit jQuery() / $

$ = function (selector, context) {
    var el = new jQuery.fn.init(selector, context);
    if (el.length === 0) throw new Error('fail : "' + selector + '" Not Found');
    return el;
}

$('body'); // okay, returns element

$('nosuchthing'); // fail, throws error
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Another way would be to just return null or undefined instead of an empty collection, and let the next function chained on throw the error

$ = function (selector, context) {
		var el = new jQuery.fn.init(selector, context);
    if (el.length === 0) return null;
    return el;
}

$('body').on('click', function() {}) // hunkydory
$('nosuchthing').on('click', function() {}) // can't read property "on" of "null"



回答2:


If you do want the error to be thrown, just use the vanilla javascript instead of the jquery function.



来源:https://stackoverflow.com/questions/45639894/how-to-catch-when-a-selector-is-passed-to-jquery-that-does-not-exist-in-docume

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!