帮助使用jQuery处理子元素/父元素 [英] Help with manipulating child/parent elements with jQuery
问题描述
当前我有这个JQuery脚本
Currently I have this JQuery script
var img = $(this);
img.wrap('<div class="photo"></div>');
img.parent().append("<p>" + img.attr("alt") + "</p>");
成功完成以下操作:
<img src="photo.jpg" alt="caption">
进入此
<div class="photo">
<img src="photos.jpg" alt="caption"/>
<p>caption</p>
</div>
一切正常,除非图像具有父链接. <a href="#"><img
,因为我希望它是正确的html(我很挑剔),因此改善以下结果效果将是令人满意的
All is well unless the image has a link as a parent; <a href="#"><img
since I want it to be correct html (I'm fussy) improving the resulting outcome bellow would be satisfactory
<a href="#">
<div class="photo">
<img src="photos.jpg" alt="caption"/>
<p>caption</p>
</div>
</a>
对此:
<div class="photo">
<a href="#">
<img src="photos.jpg" alt="caption"/>
</a>
<p><a href="#">caption</a></p>
</div>
到目前为止,这是我的jQuery脚本(不行,因为我是菜鸟)啊哈
This is my jQuery script so far (which doesn't work bc I'm a noob) aha
if(img.parent('a')){
var targetLink = img.parent('a').attr('href').val();
img.parent('a').wrap('<div class="photo"></div>');
img.parent('div').append('<p><a href="'+targetLink+'">' + img.attr("alt") + '</p></a>');
}else{
img.wrap('<div class="photo"></div>');
img.parent().append("<p>" + img.attr("alt") + "</p>");
};
任何建议或帮助将不胜感激:)
谢谢!
Any advice, or help will be greatly appreciated : )
Thank You!
更新 答案
var withLink = img.parent('a').length > 0,
targetPar = withLink ? img.parent() : img;
targetPar.wrap('<div class="photo"></div>');
if(withLink > 0){
targetPar.parent().append('<p class="caption"><a href="'+img.parent().attr('href')+'">' + img.attr('title') + '</p></a>');
}else{
img.parent().append('<p class="caption">' + img.attr('title') + '</p>');
}
推荐答案
我认为问题在于您的"if"语句,该语句应为:
I think the problem is your "if" statement, which should be:
if (img.parent('a').length) {
// ...
}
然后,当您尝试获取<a>
标记的"href"时,您正在调用"val()",这不是必需的(甚至是正确的):
Then, when you try to get the "href" of the <a>
tag, you're calling "val()" and that's not necessary (or correct, even):
var targetLink = img.parent('a').attr('href');
虽然与您的问题无关,但"alt"属性应该用于描述图像的含义,而"title"则更像是我所说的标题".换句话说,完全看不到图像的人应该可以理解"alt"文本,而标题"则是向可以看到图像的人描述的图像.只是尼特.
Also, though not relevant to your problem, the "alt" attribute is supposed to describe what the image is about, while the "title" is more like what I'd call a "caption". In other words, the "alt" text should be understandable to people who can't see the image at all, while the "title" describes an image to a person who can see it. Just a nit.;
这篇关于帮助使用jQuery处理子元素/父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!