在JavaScript中添加onclick函数转到url?

Joh*_*lor 87 javascript jquery hyperlink

我正在使用这个花哨的小JavaScript来突出显示用户在其上悬停的字段.你有没有可以告诉我是否有一种方法可以添加一个onclick函数,它将作为一个链接并转到一个URL?

<script>
         $(function() {
            $('tr').hover(function() {
                $(this).css('background-color', '#eee');
                $(this).contents('td').css({'border': '0px solid red', 'border-left': 'none', 'border-right': 'none'});
                $(this).contents('td:first').css('border-left', '0px solid red');
                $(this).contents('td:last').css('border-right', '0px solid red');
            },
            function() {
                $(this).css('background-color', '#FFFFFF');
                $(this).contents('td').css('border', 'none');
                $('a#read_message.php').click(function(){ URL(); });
            });
        });
        </script>
Run Code Online (Sandbox Code Playgroud)

Ric*_*hoe 148

尝试

 window.location = url;
Run Code Online (Sandbox Code Playgroud)

也用

 window.open(url);
Run Code Online (Sandbox Code Playgroud)

如果你想在新窗口中打开.


Aam*_*zad 115

只需使用它

onclick="location.href='pageurl.html';"
Run Code Online (Sandbox Code Playgroud)

  • 这将在同一窗口中打开链接,而接受的答案将在新窗口中打开.我更喜欢这个答案的方法 (8认同)

azz*_*y81 30

在jquery中将用户发送到不同的URL,您可以这样做:

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

这种方式也可以,但上面是更新的更正确的方法

$("a#thing_to_click").click(function(e){
         e.preventDefault();
         window.location = "http://www.google.com/";    
});
Run Code Online (Sandbox Code Playgroud)


T.W*_*ole 11

function URL() {
    location.href = 'http://your.url.here';
}
Run Code Online (Sandbox Code Playgroud)


Moj*_*oji 7

HTML

<input type="button" value="My Button" 
onclick="location.href = 'https://myurl'" />
Run Code Online (Sandbox Code Playgroud)

MVC

<input type="button" value="My Button" 
onclick="location.href='@Url.Action("MyAction", "MyController", new { id = 1 })'" />
Run Code Online (Sandbox Code Playgroud)


Dar*_*kus 6

如果您正在处理<a>标签,并且您想中断进入默认设置href,则应this改为使用。

转到默认网址(雅虎):

<a href="https://yahoo.com" onclick="location.href='https://google.com';"> 
Run Code Online (Sandbox Code Playgroud)

转到新网址(谷歌)onclick

<a href="https://yahoo.com" onclick="this.href='https://google.com';">
Run Code Online (Sandbox Code Playgroud)

通过使用this您正在中断当前的浏览器onclick事件并href在继续默认行为之前进行更改<a href='...


小智 5

如果您想在新标签页中打开链接,则可以:

$("a#thing_to_click").on('click',function(){
    window.open('https://yoururl.com', '_blank');
});
Run Code Online (Sandbox Code Playgroud)