Create link with jQuery

I would like to use JQuery to create a link button, but the code I wrote below doesn't seem to work. What is missing?

<head>
        <title>Click Url</title>
        <script src="http://code.jquery.com/jquery-latest.js"     
        type="text/javascript"></script>
            <script type="text/javascript">
                $(function() {
                    $("#Button1").click(function() {
                        $("#an1").click();
                    });
                });
    </script>
</head>
<body>
    <a href="http://google.com" id="an1">Click</a>
    <input id="Button1" type="button" value="button" />
</body>

      

+2


source to share


3 answers


The method click()

will not work with hyperlinks. Instead, $("#an1").click();

use the following to redirect to this URL:

window.location.href = 'http://google.com';

      



Or, as suggested by davidsleeps in the comments, do this:

window.location.href = $("#an1").attr("href");

      

+4


source


You are calling onclick links that are not associated with it.



The fact that you navigate to the url when you click the link is the browser and has nothing to do with javascript.

0


source


Adding this code will make it work, but again you just fire the click event. You are not actually simulating a click.

$('#an1').click(function(){
  window.location.href = $(this).attr('href');
});

      

Now when you fire the click event, it will actually change location.

0


source







All Articles