JavaScript 如果锚点的href属性为空如何隐藏span元素
任务是在标签的href属性不存在或无效的情况下隐藏标签。
假设我们在标签内部有一个标签。它将类似于下面的样式:
<span><a href="www.google.com"></a></span>
现在我们给元素添加id以便标识它们。
<span id="outer"><a id="inner" href="www.google.com"></a></span>
现在,我们需要在 < span> 标签的“href”属性为空或无效时隐藏它。
方法:
- 第一种情况是 href 为空。所以我们只需要检查 href 是否为空,这可以使用原生 JavaScript 完成。
- 第二种情况是 href 指向一个文件/位置。我们需要检查它是一个有效的文件/位置还是无效。在这种情况下,当 href 存在时,我们会使用 jQuery Ajax 调用来检查它是否指向某个有效的文件或位置。jQuery Ajax 调用可以用于在后台与 web 服务器交换数据。如果返回错误,那么文件的位置是无效的。
示例 1: 下面的代码展示了 href 为空的情况。
<span id="outer">
<a id="inner" href="">this is link</a>
</span>
<script>
if(document.getElementById("inner")
.getAttribute("href")=="") {
document.getElementById("outer")
.style.display = "none";
alert("File does not exist");
}
</script>
输出:
示例2: 下面的代码是一个当href指向一个位置时的示例。
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<span id="outer">
<a id="inner"
href=
"https://jsonplaceholder.typicode.com/todos/1">
this is link
</a>
</span>
<script>
// Function to check if url is
// valid by making Ajax call
function doesFileExist(url) {
.ajax({
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
method:'HEAD',
url:url,
success:function(){
alert("File exists!")
},
error:function(){
// Hiding the outer span tag
("#outer").hide()
alert("File does not exists!")
},
})
}
// Storing the location href is pointing to
url=$("#inner").attr("href")
doesFileExist(url)
</script>
输出: