【问题标题】:How to remove a href that is listed under div tag?如何删除 div 标签下列出的 href?
【发布时间】:2017-01-17 18:54:22
【问题描述】:
我正在修改我的 wordpress 主题的一部分,但遇到了一个问题。我想删除点击链接的功能,尽管我无法修改类名或设置 ID 标签
HTML:
<div class="one">
<a href="foobar.com">foobar.com</a>
</div>
我试图通过编写这个 JavaScript 来删除该功能:
document.getElementsByClassName("one")
.getElementsByTagName("a")
.removeAttribute("href");
但是这个方法不起作用,是我做错了吗?
【问题讨论】:
标签:
javascript
html
css
wordpress
【解决方案1】:
您可以使用 css。
.one a {
pointer-events: none;
}
你也可以通过添加cursor: default;来移除手形光标
【解决方案2】:
document.getElementsByTagName("a")[0].removeAttribute("href");
<div class="one">
<a href="foobar.com">foobar.com</a>
</div>
无需先定位.one。只需以getElementsByTagName 为目标,但请记住,这会返回一个元素数组,因此您需要引用要删除的元素的索引。
document.getElementsByTagName("a")[0].removeAttribute("href");
【解决方案3】:
如果您只需要选择“one”类中的链接,则需要对从getElementsByClass 返回的内容进行索引,然后调用 children 并对其进行索引:
document.getElementsByClassName("one")[0].children[0].removeAttribute("href")
【解决方案4】:
你可以这样做:
document.getElementById("text").onclick = function(){
var clickStatus = true; // Change this to true if you want to enable the link.
if (clickStatus){
window.location = "http://foobar.com";
}
}
<div class="one">
<section id="text">foobar.com</section>
</div>
【解决方案5】:
它将生成Type Error,因为getElementsByClassName 函数将返回节点列表而不是单个节点,因此您需要执行以下操作:
document.getElementsByClassName("one")[0]
.getElementsByTagName("a")[0]
.removeAttribute("href");
或
document.querySelector(".one a").removeAttribute("href");
以上任何方法都可以解决您的问题
希望对你有帮助
【解决方案6】:
我认为您需要在此处禁用 Href 功能。
请使用 Jquery :
$('.one > a').on('click',function(e){
e.preventDefault();
}
希望这对你有用