首页 > 解决方案 > 如果有人订阅,则在网站上隐藏 Youtube 订阅按钮

问题描述

我正在使用 google 的代码向我的 wordpress 网站添加一个 youtube 订阅按钮:

<script src="https://apis.google.com/js/platform.js"></script>
<div class="g-ytsubscribe" data-channel="GoogleDevelopers" data-layout="default" data-count="default">

当我使用浏览器的检查器时,我看到了不同的类:

我的想法是通过 CSS 用 javascript 隐藏按钮:

document.getElementsByClassName(yt-uix-button-subscribed-branded).style.visibility='hidden';

这没有用。

通过控制台我尝试调试问题:

console.log(document.getElementsByClassName("yt-uix-button-subscribed-branded"));

并且控制台显示没有类。但是我通过检查员看到了课程。我究竟做错了什么?

标签: javascripthtmlwordpress

解决方案


您可以尝试仅使用 css 并将类设置为未订阅:display: none;

.yt-uix-button-subscribe-branded {
display: none;
}
<h1 class="yt-uix-button-subscribed-branded"> Subscribed </h1>
<h1 class="yt-uix-button-subscribe-branded"> Not Subscribed </h1>


第二次尝试

在 JavaScript 中,您可以使用 .querySelector(".yt-uix-button-subscribed-brand") ,因此当它存在时,它会将父级的 innerHTML 替换为您想要的 html 标签。

const ytSubBtn = document.querySelector(".yt-uix-button-subscribe-branded");
const ytContainer = document.querySelector(".yt-sub");

if (ytSubBtn.classList.contains('yt-uix-button-subscribe-branded')) {
    ytContainer.innerHTML = "<h2 style='color: tomato;'> This is added via JS and replaces the Subscribe button</h2>"
}
*{
  font-family: helvetica;
  margin: 1rem;
}

.yt-subscribed {
  display: none;
}

.yt-sub{
  background-color: #eee;
  padding: 1rem;
}
<!-- Option 1: they are subscribed so the JavaScript gets the element by the class name and replaces the interior of yt-sub with the code you want to add.-->

<div class="yt-sub">
  <h2 class="yt-uix-button-subscribe-branded"> You're already subscribed </h2>
</div>

<!-- Option 2: they are not subscribed, so the h2 has a different class that the one we are looking in the JS, it stays the same.-->

<div class="yt-sub">
  <h2 class="yt-uix-button-subscribed-branded"> Not Subscribed </h2>
</div>


推荐阅读