javascript - 帮助使用 jQuery 操作子/父元素

标签 javascript jquery jquery-selectors parent-child dom-manipulation

目前我有这个 JQuery 脚本

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 (我很挑剔),改进下面的结果将是令人满意的

<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 脚本(这不起作用,因为我是菜鸟)啊哈

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>");
};

任何建议或帮助将不胜感激:)
谢谢!

更新 答复

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”语句,它应该是:

if (img.parent('a').length) {
  // ...
}

然后,当您尝试获取 <a> 的“href”时标签,您正在调用“val()”,这是不必要的(甚至是正确的):

  var targetLink =  img.parent('a').attr('href');

此外,虽然与您的问题无关,但“alt”属性应该描述图像的内容,而“标题”更像是我所说的“标题”。换句话说,“替代”文本对于根本看不到图像的人来说应该是可以理解的,而“标题”则向能够看到图像的人描述图像。只是一点点。;

关于javascript - 帮助使用 jQuery 操作子/父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2922925/

相关文章:

javascript - 将 React 与不受控制的第三方组件一起使用

javascript - 如何将标题属性发送到 FancyBox 画廊图像?

javascript - jQuery 选择当前脚本标签

javascript - 如何通过jQuery用replace方法更新textarea

JQuery 选择器 - 选择这个,而不是那个?

JavaScript 下载到 Excel 表格

javascript - 为什么这个 JavaScript 表达式的计算结果为 false?

javascript - 如何在调整大小时给导航 100% 宽度(以像素为单位)?

javascript - Angular 2即使没有导航到它也能保持路线活跃

javascript - 如何让用户在滑动之前悬停两秒