[英]Hiding a parent element using JS/JQuery based on the alt tag of a child element
我的投资组合网站有一个Wordpress后端,我使用Wordpress画廊生成指向我的各个项目的链接。 但是,它现在变得有些笨拙,我想让访问者能够根据类别过滤选项的数量。 例如“设计”,“图形设计”等。
画廊中的每个元素都使用以下代码:
<dl class='gallery-item'>
<dt class='gallery-icon landscape'>
<a href="Page Link" target="_self" class="no-lightbox"><img width="250" height="250" src="Display Image" class="attachment-full" alt="Design" /></a>
</dt>
<dd class='wp-caption-text gallery-caption'>
Description of Page
</dd>
</dl>
声明img时,我可以控制alt标签的文本。 我要寻找的是设计一个链接,该链接调用一个JavaScript函数,如果子img元素具有特定的alt标签,该链接将隐藏父元素。
这是可以做到的吗? 我已经看过并且一直在尝试几种方法,但是到目前为止我还没有接近。
是的,您可以根据孩子的属性隐藏父母:
Js(香草):
//Consider "el" as the <a> clicked element
if(el.children[0].getAttribute("alt") == "Something") {
el.parentNode.style.display = "none";
}
jQuery:
//Consider "el" as the <a> clicked element
if($(el).find("img").is("[alt='Something']")) {
$(el).parent().hide();
}
但是如前所述,您应该为alt
设置另一个属性,因为alt
具有不同的用途...
正如其他人提到的那样,您可以将其放在一个更适合此类应用程序的data属性中,但是鉴于此处具有的特定上下文,类似以下内容:
$("#hideDesign").click(function() {
$("[alt='Design']").parent().toggle();
})
其中“ #hideDesign”是您希望用户单击以切换该特定类型的元素的视图的元素的ID。
假设您无法操纵img
标签并为它们提供data
属性,则仍然可以依靠alt
属性来实现。
只是为了说明,我正在考虑以下标记:
<select id="mySelect">
<option value="">Please select...</option>
<option value="Design">Design</option>
<option value="Graphic Design">Graphic Design</option>
</select>
<br />
<dl class='gallery-item'> <dt class='gallery-icon landscape'>
<a href="Page Link" target="_self" class="no-lightbox"><img width="250" height="250" src="Display Image" class="attachment-full" alt="Design" /></a>
</dt>
<dd class='wp-caption-text gallery-caption'>Description of Page</dd>
</dl>
<dl class='gallery-item'> <dt class='gallery-icon landscape'>
<a href="Page Link" target="_self" class="no-lightbox"><img width="250" height="250" src="Display Image" class="attachment-full" alt="Graphic Design" /></a>
</dt>
<dd class='wp-caption-text gallery-caption'>Description of Page</dd>
</dl>
并使用jQuery:
$(function () {
// When the user selects a gallery item to display.
$('#mySelect').on('change', function () {
// We hide all of them.
$('.gallery-item').hide();
// If there's actually something selected.
if ($(this).val()) {
// Select the image which alt is the value selected,
// and show its parent which class is gallery-item.
$('[alt="' + $(this).val() + '"]').parents('.gallery-item').show();
}
});
});
只是为了补充,反过来:
$(function () {
// When the user selects a gallery item to hide.
$('#mySelect').on('change', function () {
// We show all of them.
$('.gallery-item').show();
// If there's actually something selected.
if ($(this).val()) {
// Select the image which alt is the value selected,
// and hide its parent which class is gallery-item.
$('[alt="' + $(this).val() + '"]').parents('.gallery-item').hide();
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.