[英]Show/Hide Divs based on Anchor Href attr that matches the Hash in the URL
[英]Hide Anchor tag based on href URL
我想知道是否有可能隱藏指向特定URL的錨標記。 我知道可以使用JavaScript像這樣隱藏id:
document.getElementById('someID').style.display = 'none';
<a href="#" id="someID" style="display: none">Check</a>
但是,假設我要根據網址示例隱藏所有錨定標記:www.example.com
<a href="www.example.com" id="someID" style="display: none">Check</a>
<a href="www.example2.com" id="someID" style="display: none">Check</a>
我想隱藏第一個錨標簽,而不是第二個引用example2.com的標簽
純JavaScript而不是jQuery是否可行?
您可以使用document.querySelector
這樣選擇bu屬性值。我沒有使用jquery,僅使用了JavaScript。
document.querySelector("[href='www.example.com']").style.display = 'none';
<a href="www.example.com" id="someID" style="display:block">Check</a> <a href="www.example2.com" id="someID" style="display:block">Check</a>
只需遍歷所有錨元素,然后檢查其href
:
var anchors = document.getElementsByTagName('a'); for (var i = 0; i < anchors.length; i++) { if (anchors[i].href == 'https://example.com/') { anchors[i].style.display = 'none'; } }
<a href="https://example.com/" id="someID">Check</a> <a href="https://example2.com/" id="someID">Check</a>
你可以創造條件
var url = document.getElementsByTagName('a');
if (url.href = "www.example.com")
{
url.style.display = none;
}
這不是確切的代碼。 我提供了示例。請嘗試一下,讓我知道。 這是單身。 如果你有很多標簽,那么循環所有這些
您可以使用javascript來完成這項工作。 使用querySelector
獲取具有相同id
所有元素。 然后循環ids
並比較href
鏈接值。
<script>
var elements = document.querySelectorAll("[id='someID']");
for(var i = 0; i < elements.length; i++) {
if (elements[i].getAttribute("href") === "www.example.com") {
elements[i].style.display='none';
}
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.