How to catch when a selector is passed to jQuery()

2019-08-07 08:35发布

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?

2条回答
在下西门庆
2楼-- · 2019-08-07 08:51

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

查看更多
走好不送
3楼-- · 2019-08-07 08:52

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"

查看更多
登录 后发表回答