jQuery - 如何确定父元素是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2691873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:04:45  来源:igfitidea点击:

jQuery - How to determine if a parent element exists?

jqueryparent

提问by Dan

I'm trying to dynamically and a link to an image, however I cannot correctly determine is the parent link already exists.

我正在尝试动态链接到图像,但是我无法正确确定父链接是否已经存在。

This is what I have,

这就是我所拥有的

if (element.parent('a'.length) > 0)
{   
      element.parent('a').attr('href', link);            
}
else
{   
      element.wrap('<a></a>');
      element.parent('a').attr('href', link);     
}

Where element refers to my img element and link refers to the url to use.

其中 element 是指我的 img 元素,link 是指要使用的 url。

Every time the code runs, the else clause is performed, regardless of whether or not the img tag is wrapped in an a tag.

每次代码运行时,都会执行 else 子句,而不管 img 标签是否包含在 a 标签中。

Can anyone see what I'm doing wrong?

谁能看到我做错了什么?

Any advice appreciated.

任何建议表示赞赏。

Thanks.

谢谢。

回答by RoToRa

The first line should be:

第一行应该是:

if (element.parent('a').length > 0)

回答by cletus

Assuming elementis actually a jQuery object:

假设element实际上是一个 jQuery 对象:

if (!element.parent().is("a")) {
  element.wrap("<a>")
}  
element.parent().attr("href", link);

If elementis a DOM node:

如果element是 DOM 节点:

if (!$(element).parent().is("a")) {
  $(element).wrap("<a>")
}  
$(element).parent().attr("href", link);

回答by SLaks

Your code is parsed as a call to element.parentwith the argument 'a'.length.
It is therefore equivalent to element.parent(1), which is an invalid call.

您的代码被解析为element.parent对参数的调用'a'.length
因此element.parent(1),它等效于,这是一个无效调用。

You need to get the length of the jQuery object by moving .lengthafter the ), like this:

您需要通过在.length之后移动来获取 jQuery 对象的长度),如下所示:

if (element.parent('a').length > 0)

Also, this will not work if elementis nested in some other tag which is itself in an <a>tag.
You might want to call closestinstead.

此外,如果element嵌套在其他标签中,这本身就在<a>标签中,这将不起作用。
您可能想改为打电话closest