停止<a> tag from loading href value

时间:2018-02-15 12:06:39

标签: javascript jquery

I have something like this:

<a href="http://example.com">
   <span>text</span>
   <button class="hello">hello</button>
</a>

When user clicks the <button> I don't want the page to go to the href value of the parent <a> tag. Is there any way to stop it from redirecting without moving the button outside of the anchor tag?

So hooking into the button:

jQuery( document ).on( 'click', '.hello', function() {
    // STOP redirect
});

What's the solution?

5 个答案:

答案 0 :(得分:5)

您可以使用breadButton.addActionListener(new ActionListener () { public void actionPerformed(ActionEvent e) { try{ String breadStock = new String(Files.readAllBytes(Paths.get("bread.txt"))); int breadNumber = Integer.parseInt(breadStock); String soldStock = new String(Files.readAllBytes(Paths.get("soldStock.txt"))); int sold2Number = Integer.parseInt(soldStock); int bNumber = breadNumber - sold2Number; System.out.println(bNumber); }catch(IOException b){ b.printStackTrace(); } } }); 阻止该网页转到href网址。

e.preventDefault();
jQuery(document).on('click', '.hello', function(e) {
  e.preventDefault();
});

Doc:https://api.jquery.com/event.preventdefault/

答案 1 :(得分:1)

所以你可以这样做:

<a href="www.example.com">
   <span>text</span>
   <button class="hello" id="btnhello">hello</button>
</a>

然后

$('#btnhello').onclick((ev) => {
  ev.preventDefault();
  ev.stopPropagation();
});

您可以使用按钮来调用事件阻止默认值,因此许多浏览器都不会执行提交默认行为,并且事件stopPropagation不允许将事件传播到父级,即单击按钮时的锚点。

答案 2 :(得分:1)

你尝试过这段代码吗?

window.jQuery('.hello').click(function(event){ event.preventDefault(); alert("YaY!"); });

答案 3 :(得分:0)

是的,您可以使用preventdefault - 它会阻止标准行为,或者您可以在点击功能中返回false

<a href="/" onclick="return false">Press </a>
     or 
<a href="/" onclick="event.preventDefault()">Press </a>

答案 4 :(得分:0)

ruturn false会阻止它将其重定向到任何其他页面:

jQuery( document ).on( 'click', '.hello', function() {
    // your Code goes here
    // STOP redirect
    return false;
});