开发者

Create Link Button with JQuery

开发者 https://www.devze.com 2022-12-08 02:11 出处:网络
I\'d like to use JQuery to create a link button, but the code I wrote below doesn\'t seem to work. What is missing?

I'd 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://c开发者_JS百科ode.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>


The click() method will not work on hyperlinks. Instead of $("#an1").click(); to redirect to that URL, use this:

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

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

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


You are invoking the links onclick event, which doesn`t have anything bound to it.

The fact that you transfer to a url when you click a link is browser behavior and has nothing to do with javascript.


Adding this code would make it work, but again you're just firing the click event. You're 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 the location.

0

精彩评论

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

关注公众号