仅在启用JavaScript的情况下(如果禁用了Javascript则执行href),如何仅在Anchor标记中调用Onclick?

时间:2019-03-04 12:27:24

标签: javascript html anchor

仅在启用JavaScript的情况下,如何才能在Anchor标记中调用Onclick,以防禁用Javascript后执行href?

2 个答案:

答案 0 :(得分:0)

仅在启用JavaScript的情况下,JavaScript才能运行。

在单击链接时(这是默认行为),href会自动跟随。除非使用JavaScript来阻止它。

function onClick(event) {
  event.preventDefault();
  console.log("JavaScript function called");
}
const link = document.querySelector("a");
link.addEventListener("click", onClick);
<a href="http://example.com/">Link</a>

答案 1 :(得分:-2)

请详细说明为什么要检查是否禁用Java脚本以执行href。 要检查Java脚本禁用,您可以参考以下链接以供参考。

How to detect if JavaScript is disabled?

编辑::如果禁用了javascript,则用html编写的函数将自动失败,并且href将被执行。请检查以下代码。

<!DOCTYPE html>
<html>
<body>

<script>
document.write("Hello World!")
function test()
{
alert('okoko');
return false;
}

</script>
<noscript>Sorry, your browser does not support JavaScript!</noscript>

<a href="http://google.com" onclick="return test();">test</a>
<p onclick="">A browser without support for JavaScript will show the text inside the noscript element.</p>

</body>
</html>

enter image description here

enter image description here

enter image description here

根据上述屏幕截图,可以确认禁用Java脚本后href将自动执行。

希望这个答案对您有帮助。

相关问题