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

发布于 2024-08-29 20:27:15 字数 445 浏览 2 评论 0原文

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

这就是我所拥有的,

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

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

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

谁能看到我做错了什么吗?

任何建议表示赞赏。

谢谢。

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.

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

Can anyone see what I'm doing wrong?

Any advice appreciated.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

污味仙女 2024-09-05 20:27:15

第一行应该是:

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

The first line should be:

if (element.parent('a').length > 0)
静若繁花 2024-09-05 20:27:15

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

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

如果 element 是一个 DOM 节点:

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

Assuming element is actually a jQuery object:

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

If element is a DOM node:

if (!$(element).parent().is("a")) {
  $(element).wrap("<a>")
}  
$(element).parent().attr("href", link);
过去的过去 2024-09-05 20:27:15

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

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

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

此外,如果 element 则这将不起作用嵌套在某个其他标签中,而该标签本身又位于 标签中。
您可能想改为调用closest

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

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文