问题
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