当它与元素不匹配时,使jQuery抛出错误 [英] Make jQuery throw error when it doesn't match an element

查看:124
本文介绍了当它与元素不匹配时,使jQuery抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,当我使用jQuery选择一个元素时,如果没有找到匹配的元素,我宁愿给我一个错误。



例如,我刚刚遇到一个错误,因为我更改了一个 ul 元素的类:

  $('ul.some-list')。append(listItem)

是有一个方便的方法来确保我的jQuery调用与元素匹配?

解决方案

你可以使用一个插件来确保jQuery对象不为空:

  $。fn.ensure = function(){
if(this.length = == 0)throw空jQuery结果。
返回这个;
}

用法:

  $( 'ul.some列表')确保()追加(的listItem)。; 


Usually, when I'm selecting an element with jQuery, I would prefer it give me an error if it doesn't find matching element.

For example, I just had a bug where this failed because I changed the class of a ul element:

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

Is there a convenient method for ensuring that my jQuery call matched an element?

解决方案

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);

这篇关于当它与元素不匹配时,使jQuery抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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