简体   繁体   English

jQuery和选择器:如何确保确实存在我要查找的元素?

[英]jQuery and selectors: how can I make sure that there really is the element I'm looking for?

I'm no experienced JavaScript developer (I know quite a lot about Ruby, though), and so far, when I had to implement some lines of JS, it seemed enough to use jQuery and hack together something. 我不是经验丰富的JavaScript开发人员(不过,我对Ruby的了解很多),到目前为止,当我必须实现一些JS行时,似乎足以使用jQuery并一起破解了。

As far as I understand jQuery, it doesn't assume HTML elements to really be there, but it simply executes a query, and if there is a matching element (or many), some stuff is done with it. 据我了解jQuery的,它不承担HTML元素真的存在,但它只是执行查询时,如果一个匹配的元素(或多个),有些东西是用它做。 This works well for generic code which may want to apply some action to some elements on a page (which may be there or not), but when it comes to specific logic, it's a problem. 这对于通用代码可能效果很好,该通用代码可能想要对页面上的某些元素(可能存在或不存在)应用某些操作,但是当涉及到特定逻辑时,这是一个问题。

What do I mean with this? 这是什么意思? Let me give an example. 让我举个例子吧。

Let's suppose I have one single page with one single HTML element (with the ID '#my_element'). 假设我有一个页面和一个HTML元素(ID为“ #my_element”)。 For exactly this page I have to run some JS code, and I have to be sure that it finds this element and does the things to it that I want. 对于此页面,我必须运行一些JS代码,并且必须确保它找到了此元素并对其执行所需的操作。

Doing this with jQuery, I simply do something like $('#my_element').addTooltip() , which seems fine first: when I hover over the element, a tooltip is displayed. 使用jQuery进行此操作,我只需要执行类似$('#my_element').addTooltip() ,该操作首先看起来不错:当我将鼠标悬停在元素上时,会显示一个工具提示。

Let's assume that some months later I already have completely forgotten about this JS script, and I change the ID of the element to something else. 假设几个月后我已经完全忘记了这个JS脚本,并且将元素的ID更改为其他名称。 What happens? 怎么了? Nothing. 没有。 I won't notice the problem with the missing tooltip until I stumble over it by accident. 直到偶然发现它时,我才会注意到缺少工具提示的问题。

So I wonder how I can make sure that my JS is really applied, which means: the required elements are found, the stuff is done to them, etc. 因此,我想知道如何确保真正应用了我的JS,这意味着:找到了所需的元素,对它们进行了处理,等等。

Is jQuery's philosophy the "wrong" tool for this? jQuery的哲学是“错误”的工具吗? Do I need another framework? 我需要另一个框架吗? Maybe something more sophisticated pattern, eg something like MVC? 也许是更复杂的模式,例如MVC? I played with KnockoutJS before, and it seems that this may be better for this, as it's bound directly to elements using data-bind attributes, so it fits tighter on the code than jQuery does. 我以前玩过KnockoutJS,似乎这样做可能更好,因为它使用data-bind属性直接绑定到元素,因此它比jQuery更适合代码。

The comments mentioned always checking the .length property before performing actions on returned results (which is probably the best answer,) but in the case of an actual syntax error your statement that "nothing happens" isn't always true. 提到的注释总是在对返回的结果执行操作之前检查.length属性(这可能是最好的答案),但是在实际语法错误的情况下,“什么都没有发生”的陈述并不总是正确的。

If you're using Chrome developer tools or a similar tool in another browser (firebug, etc.) you should see the error in the "Console" 如果您在其他浏览器中使用Chrome开发人员工具或类似工具(Firebug等),则应在“控制台”中看到错误

You can also turn on javascript debugging for more information. 您也可以打开javascript调试以获取更多信息。 When you call the "addTooltip()" on something which is null (the jQuery collection) you'll see an error pop up in the Console and may get an exception in the debugger. 当您在null值(jQuery集合)上调用“ addTooltip()”时,您会在控制台中看到错误弹出窗口,并且可能在调试器中得到异常。

This is one of the easiest ways to find errors in your client-side javascript. 这是在客户端javascript中查找错误的最简单方法之一。

You could add a specific plugin to verify the existence of a non-zero- length collection, and use that in the chain: 您可以添加特定的插件来验证是否存在非零长度的集合,并在链中使用它:

(function ($) {
  $.fn.verify = function() {
    if (this.length) {
      return this;
    }
    else {
      console.log("No elements found with supplied selector.")
    }
  }
})(jQuery);

$("#myElement").verify().addTooltip();

This does, of course, rely on the verify() plugin being manually applied, there is – to the best of my knowledge – no error-reporting built in to jQuery to automatically enable logging of invalid selectors, or reporting of selectors returning zero elements. 当然,这确实依赖于手动应用的verify()插件,据我所知,jQuery没有内置错误报告功能来自动启用无效选择器的记录,或者报告返回零元素的选择器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM