如何在<a> tag to prevent link being followed?

时间:2017-03-06 09:29:36

标签: javascript html css

I've added a button inside a link tag, with a little cross image, that I will eventually use to actually remove that element without it following the link also:

function detectClick(message) {
  window.alert("Detected: " + message);
}
<div><a style="border: solid 1px black; vertical-align: middle; display:inline-block;" href="http://www.google.com"><button style="position: relative; float: right;" onclick="detectClick('Google')"><img src="cross.png"></button>Google</a></div>

How do I consume that click, once it has executed detectClick(...), in order to prevent navigation away from the current page?

NOTE: Ideally, without using jQuery.

5 个答案:

答案 0 :(得分:3)

首先将您的功能更改为:

function detectClick(message){
    window.alert("Detected: " + message);
    return false; // add this line
}

然后将onclick处理程序更改为:

onclick="return detectClick('Google')" // note the "return"

请注意,HTML标准的AFAIK不允许在锚点内有按钮。

答案 1 :(得分:1)

<script type="text/javascript">
 function detectClick(message){
  window.alert("Detected: " + message);
  return false;
 }
</script>

答案 2 :(得分:1)

return false;结尾处需要detectClick,您需要在onclick事件中返回detectClick。

解释:事件处理程序的return值告诉浏览器是否应该发生默认浏览器操作。由于默认情况下click按钮会触发其父级的click事件,因此链接return false;会阻止默认情况发生,这是您的确切意图。

答案 3 :(得分:0)

&#13;
&#13;
<html>
<head>
<title>Consume Click Test</title>    
</head>
<body>
    <div><a style="border: solid 1px black; vertical-align: middle; display:inline-block;" href="javascript:void 0;"><button style="position: relative; float: right;" onclick="detectClick('Google')"><img src="cross.png"></button>Google</a></div>
</body>
</html>
<script type="text/javascript">
    function detectClick(message){
        window.alert("Detected: " + message);
    }
</script>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

从链接标记中删除您的href标记。在该链接标记中添加ID。并在detectClict()中指定href值。像 - &GT;

SELECT * FROM accounts WHERE accounts.First_Name in
(SELECT a.First_Name
 FROM accounts a
 INNER JOIN accounts b
 ON a.Person_Number = b.Person_Number
 WHERE a.First_Name = b.First_Name
 AND a.Bank_Account_Name <> b.Bank_Account_Name
 );