javascript - 如果有人订阅,则在网站上隐藏 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">
当我使用浏览器的检查器时,我看到了不同的类:
- 当我订阅时:yt-uix-button-subscribed-brand
- 当我没有订阅时:yt-uix-button-subscribe-brand
我的想法是通过 CSS 用 javascript 隐藏按钮:
document.getElementsByClassName(yt-uix-button-subscribed-branded).style.visibility='hidden';
这没有用。
通过控制台我尝试调试问题:
console.log(document.getElementsByClassName("yt-uix-button-subscribed-branded"));
并且控制台显示没有类。但是我通过检查员看到了课程。我究竟做错了什么?
解决方案
您可以尝试仅使用 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>
推荐阅读
- css - React Material UI:框在 y 轴上不可滚动
- excel - Application.ScreenUpdating 切换
- python - 如何将 STIX 对象转换为 Pydantic 模型?
- docker - Docker Swarm 中的容器无法访问互联网
- python - 如何实现从一个 QTreeView 拖放到另一个 QTreeView?
- arrays - 从列表中查找一个单词的所有字谜
- python - 如何从 c# 应用程序运行 python 可执行文件(dummy.exe)
- excel - Excel 用 =IF 写入另一个单元格
- python - python 3.9 的 NetfilterQueue 类似物
- javascript - 我正在尝试通过匹配键名从 JSON 文件中获取值,但它不适用于嵌套键