简体   繁体   English

原型等效于jQuery最接近的函数

[英]Prototype equivalent for jQuery closest function

Is there any equivalent in Prototype for the jQuery closest function? 在jQuery最近函数的Prototype中是否有任何等价物?

http://api.jquery.com/closest/ http://api.jquery.com/closest/

thanks 谢谢

You can use the up method. 您可以使用up方法。 It is not quite equivalent, since closest also considers the current element. 它不太相同,因为closest也考虑当前元素。 So you would need to first test your selected element to see if it matches your criteria, if it does not, use the up -method: 因此,您需要首先测试所选元素以查看它是否符合您的条件,如果不符合,请使用up -method:

jQuery:
return $('#id').closest('li');

Prototype:
var element = $('id')
return element.match('li') ? element : element.up('li');
}

Comparison: 比较:

.closest() .closest()

  • Begins with the current element 从当前元素开始
  • Travels up the DOM tree until it finds a match for the supplied selector 向上移动DOM树,直到找到所提供选择器的匹配项
  • Returns a jQuery object that contains zero or one element 返回包含零个或一个元素的jQuery对象

.up() .UP()

  • Begins with the parent element 从父元素开始
  • Travels up the DOM tree until it finds a match for the supplied selector 向上移动DOM树,直到找到所提供选择器的匹配项
  • Returns an extended Element object, or undefined if it doesn't match 返回扩展的Element对象,如果不匹配则返回undefined

You can easily extend Prototype to include this method for all elements like so: 您可以轻松地扩展Prototype,以便为所有元素包含此方法,如下所示:

// Adds a closest-method (equivalent to the jQuery method) to all 
// extended Prototype DOM elements
Element.addMethods({
   closest: function closest (element, cssRule) {
      var $element = $(element);
      // Return if we don't find an element to work with.
      if(!$element) {
         return;
      }
      return $element.match(cssRule) ? $element : $element.up(cssRule);
   }
});

.next('.className') or .next('divId') .next('.className').next('divId')

There is also .previous() , .down() and .up() , depending on where you're looking. 还有.previous() .down().up() ,具体取决于你在哪里寻找。

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

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