target与现有的jQuery对象匹配

target与现有的jQuery对象匹配

本文介绍了将event.target与现有的jQuery对象匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该怎么做?

event.target返回一个HTML对象,

event.target returns a HTML object,

我的元素是一个jQuery对象.

and my element is a jQuery object.

除了比较ID或类之外,是否还有更好的方法来找出event.target = my_jquery_object?

Is there a better way to find out if event.target = my_jquery_object, besides comparing IDs or classes?

我想确保它是同一个对象,而不仅仅是具有相似类的元素...

I want to make sure that it's the same object, not just a element with a similar class...

我尝试过$(event.target) !== the_element,但失败了

the_element在开头定义为$('.something', $(this))

the_element is defined at the begining as $('.something', $(this))

我要做的是,当用户在框外单击时使框关闭,但要确保未在首先打开框的链接上单击.

What I am trying to do is to make a box close when the user clicks outside of it, but with the condition that the click wasn't made on the link that opened the box in the first place.

所以我有这个:

$(document).click(function(event){
  if(($(event.target).parents().index(box) == -1)
    && box.is(':visible')){
      close();
  }

});

我想添加另一个条件,以验证未单击打开框的链接.

And I want to add another condition that verifies that the click wasn't made on the link that opened the box.

这可行,但是我不喜欢它:

This works, but I don't like it:

if($(event.target).attr('id') != the_element)

:)

推荐答案

您可以使用.get(0)或仅使用the_element[0]从jQuery获取实际的DOM元素.不过,最好使用jQuery检查.

You can get the actual DOM element from the jQuery using .get(0) or simply the_element[0]. It would probably be better to check with jQuery, though.

if (the_element.is(event.target))
{
    ...
}

使用您的示例:

$(document).click(function(event){
  if (the_element.is(event.target)) {
      return false;
  }
  if(($(event.target).parents().index(box) == -1)
    && box.is(':visible')){
      close();
  }

});

这篇关于将event.target与现有的jQuery对象匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:57