如果href字符串包含hide parent

时间:2017-05-15 13:41:09

标签: javascript jquery

如果div类为list-view且文章a href包含字符串staticcards则隐藏文章&显示带有href字符串listcards

的文章

如果div类为card-view且文章a href包含字符串listcards,则隐藏文章&显示带有href字符串staticcards

的文章

以下是代码,不起作用

if ($(".cards-wrapper").hasClass("list-view")) {

  $('a[href*="staticcard"]').parent().hide();
  $('a[href*="listcard"]').parent().show();

} else if ($(".cards-wrapper").hasClass("card-view")) {

  $('a[href*="staticcard"]').parent().show();
  $('a[href*="listcard"]').parent().hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cards-wrapper list-view">
  <article>
    <a href="xxxxx?staticcard">Static Card</a>
  </article>
  <article>
    <a href="xxxxx?listcard">List Card</a>
  </article>
</div>

1 个答案:

答案 0 :(得分:0)

模块化,清洁然后使用它。

var wrapper = document.getElementsByClassName("cards-wrapper")[0];
if (Array.from(wrapper.classList).indexOf("list-view") > 0) {
Array.from(wrapper.getElementsByTagName("a")).filter(e=>e.href.indexOf("staticcard")>1).map(q=>q.style="display:none;");
}else {
Array.from(wrapper.getElementsByTagName("a")).filter(e=>e.href.indexOf("listcard")>1).map(q=>q.style="display:none;");
}
<div class="cards-wrapper card-view">
  <article>
    <a href="xxxxx?staticcard">Test 1</a>
  </article>
  <article>
    <a href="xxxxx?listcard">Test 2</a>
  </article>
</div>

var wrapper = document.getElementsByClassName("cards-wrapper")[0];
if (Array.from(wrapper.classList).indexOf("list-view") > 0) {
Array.from(wrapper.getElementsByTagName("a")).filter(e=>e.href.indexOf("staticcard")>1).map(q=>q.style="display:none;");
}else {
Array.from(wrapper.getElementsByTagName("a")).filter(e=>e.href.indexOf("listcard")>1).map(q=>q.style="display:none;");
}
<div class="cards-wrapper list-view">
  <article>
    <a href="xxxxx?staticcard">Test 1</a>
  </article>
  <article>
    <a href="xxxxx?listcard">Test 2</a>
  </article>
</div>