开发者

On click, click something else, prevent default. How do I do this properly with jQuery?

开发者 https://www.devze.com 2023-01-26 03:29 出处:网络
What I want to happen is, when you click a link (id=\"dontFollow\"), it triggers a click on a different link(id=\"follow\") and stops you from following the original link.

What I want to happen is, when you click a link (id="dontFollow"), it triggers a click on a different link(id="follow") and stops you from following the original link.

This is how I thought it should be done-

$("#dontFollow").click(function(e){
   $("#follow").click();
   e.preventDefault();
});

... but it's not working. Whats wrong with my code?

UPDATE: This is a little more tricky than I originally explained. It appears that I need to "click" on the other link to开发者_开发知识库 trigger some other events to cause my page to slide to the anchor. Your suggestions for "window.location" does change the window location but it's not triggering my slide events.


$("#dontFollow").click(function(){
   window.open($("#follow").attr('href'));
   return false;
});


just return false


Simply have the function return false;


I don't think you can "click a link" programmatically, you can however navigate by setting window.location.href

$('#dontFollow').attr('href','#').click(function(){
  window.location.href = $('#follow').attr('href');
});


Your code is correct. Using e.preventDefault() will prevent you from following the link being clicked.

You have't stated what specifically isn't working, but if you're trying to visit the href of the other link, then do this:

$("#dontFollow").click(function(e){
   window.location = $("#follow").attr('href');
   e.preventDefault();
});
0

精彩评论

暂无评论...
验证码 换一张
取 消