Adding an onclick function to go to url in JavaScript?

前端 未结 9 1222
北荒
北荒 2020-11-29 18:28

I am using this fancy little JavaScript to highlight a field as the user hovers over it. Could you please tell me if there is a way of adding an onclick functio

相关标签:
9条回答
  • 2020-11-29 18:43

    HTML

    <input type="button" value="My Button" 
    onclick="location.href = 'https://myurl'" />
    

    MVC

    <input type="button" value="My Button" 
    onclick="location.href='@Url.Action("MyAction", "MyController", new { id = 1 })'" />
    
    0 讨论(0)
  • 2020-11-29 18:47

    Simply use this

    onclick="location.href='pageurl.html';"
    
    0 讨论(0)
  • 2020-11-29 18:53

    In jquery to send a user to a different URL you can do it like this:

    $("a#thing_to_click").on('click', function(){
         window.location = "http://www.google.com/";    
    });
    

    this way will work too but the above is the newer more correct way to do it these days

    $("a#thing_to_click").click(function(e){
             e.preventDefault();
             window.location = "http://www.google.com/";    
    });
    
    0 讨论(0)
  • 2020-11-29 18:54

    Not completely sure I understand the question, but do you mean something like this?

    $('#something').click(function() { 
        document.location = 'http://somewhere.com/';
    } );
    
    0 讨论(0)
  • 2020-11-29 18:57

    Try

     window.location = url;
    

    Also use

     window.open(url);
    

    if you want to open in a new window.

    0 讨论(0)
  • 2020-11-29 18:57

    In case you're dealing with <a> tag, and you want to interrupt going to the default href you should use this instead.

    Go to default url (yahoo):

    <a href="https://yahoo.com" onclick="location.href='https://google.com';"> 
    

    Go to new url (google) onclick:

    <a href="https://yahoo.com" onclick="this.href='https://google.com';">
    

    By using this you're interrupting the current browser onclick event and changing href before continuing to default behaviour of <a href='...

    0 讨论(0)
提交回复
热议问题