jQuery-如何确定父元素是否存在? [英] jQuery - How to determine if a parent element exists?

查看:185
本文介绍了jQuery-如何确定父元素是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这就是我所拥有的,

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

其中元素是指我的img元素,链接是指要使用的网址.

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

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

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?

任何建议表示赞赏.

谢谢.

推荐答案

第一行应为:

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

这篇关于jQuery-如何确定父元素是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆