如何使用JavaScript禁用锚点?

kri*_*hna 9 html javascript css

我必须根据条件禁用锚链接如果某些数据到达该字段它应该作为超链接工作,如果该数据没有来,那么链接不应该在那里?对此有任何想法都是受欢迎的.

ale*_*lex 16

我无法理解你的问题正文,所以我会回答你问题的标题......

如何使用javascript禁用锚点?

JavaScript的

if (condition) {
    document.getElementsByTagName('a')[0].removeAttribute('href');
}
Run Code Online (Sandbox Code Playgroud)

jQuery的

...因为每个人都使用它,对吗?

if (condition) {
    $('a').first().removeAttr('href');
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为*甚至jQuery*可能会因`removeAtt`而失败:) (3认同)
  • 这也适用于document.getElementById(_yourIdHere _).removeAttribute('href'); (2认同)

Jah*_*hid 15

情况1:

要禁用:

document.getElementById(id).style.pointerEvents="none";
document.getElementById(id).style.cursor="default";
Run Code Online (Sandbox Code Playgroud)

启用:

document.getElementById(id).style.pointerEvents="auto";
document.getElementById(id).style.cursor="pointer";
Run Code Online (Sandbox Code Playgroud)

案例2:

如果你想要链接消失(不只是禁用它):

document.getElementById(id).style.display="none";
Run Code Online (Sandbox Code Playgroud)

把它拿回来:

document.getElementById(id).style.display="block"; //change block to what you want.
Run Code Online (Sandbox Code Playgroud)

案例3:

如果你想隐藏它,保留它的空间:

document.getElementById(id).style.visibility="hidden";
Run Code Online (Sandbox Code Playgroud)

要取回它:

document.getElementById(id).style.visibility="visible";
Run Code Online (Sandbox Code Playgroud)

  • 这很好,因为它适用于有 href 或 onclick 的情况。 (2认同)