How to call a href by onclick event of a button?

雨燕双飞 提交于 2019-12-31 04:15:11

问题


I have the following a href I use to open jquery dialogs, which works fine. Basically, the openDialog class has attached the jquery dialog code:

 <a class='openDialog' data-dialog-id='myEditDlg' data-dialog-autosize='false' data-dialog-alt='580' data-dialog-larg='740' data-dialog-title='test dialog' href='/mycontroller/EditDlg/myid'></a>

Now, I'd like to call it by the onclick event of a button. Basically, I'd like to have the same behaviour of the clicked <a class='openDialog' href when I click a button. How can I do it?**


回答1:


If I get you question right then may be jQuery trigger()(?) is what you are looking for. Example:

<button id="bt">Click</button>
<a href="example.com" id="ex">Triggerable link</a>

<script type="text/javascript">
  $('#bt').click(function() {
       $('#ex').click();
  });
</script>



回答2:


You can emulate the click by

 $('#link').click();//No arguments inside the call.

This will emulate the click event on the link. It is the same as clicking on the link. This ofcourse won't change the location if you have an event handler that stops the default behavior of the link If you want to redirect to the href attribute you can use:

 location.href=$('#link').attr('href');

So if you want to call this on click of a button.

$('#button').click(function(){$('#link').click();
   location.href=$('#link').attr('href');//In case the page doesn't change although you want it to
}


来源:https://stackoverflow.com/questions/9444243/how-to-call-a-href-by-onclick-event-of-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!