使用 jquery 使 div 可点击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5270599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:51:27  来源:igfitidea点击:

make div clickable with jquery

jquery

提问by J82

jsfiddle: http://jsfiddle.net/FgZnK/1/

jsfiddle:http: //jsfiddle.net/FgZnK/1/

Clicking on the box goes to a page not found. How can I make this work?

单击该框会转到未找到的页面。我怎样才能使这项工作?

HTML

HTML

<div class="myBox"></div>

jQuery

jQuery

$(".myBox").click(function(){
    window.location=$(this).attr("http://google.com");
     return false;
});

回答by Pawe? Go?cicki

This is the correct code:

这是正确的代码:

$(".myBox").click(function() {
    window.location = "http://google.com";
});

回答by Alex Wayne

http://jsfiddle.net/FgZnK/2/

http://jsfiddle.net/FgZnK/2/

HTML

HTML

<div class="myBox" data-href="http://google.com/">
</div>

JS

JS

$(".myBox").click(function(){
    window.location = $(this).attr("data-href");
    return false;
});

回答by Alnitak

In this chunk here:

在这个块中:

$(".myBox").click(function(){
window.location=$(this).attr("http://google.com");
 return false;
});

You're actually trying to read the non-existent attribute namedhttp://google.com.

您实际上是在尝试读取名为的不存在的属性http://google.com

Instead, just use:

相反,只需使用:

$(".myBox").click(function(){
    window.location = 'http://google.com';
});

If instead you want the actual destination to be in the mark up rather than the script, use:

相反,如果您希望实际目的地在标记中而不是在脚本中,请使用:

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

and put an hrefattribute on your DIV, just like you would on an A link.

href在 DIV 上放置一个属性,就像在 A 链接上一样。

There's no need for return falsein any of these handlers because a DIV doesn't have a default action that needs preventing, unlike a normal link.

有没有必要return false在这些处理器中,因为一个DIV没有一个默认的行动,需要预防,不像一个正常的链接。

回答by PJ Brunet

Open in new window....

在新窗口中打开....

    $("#whatever").click(function() {
        window.open(
          'https://www.example.com',
          '_blank' // open in new window
        );
    });

回答by krtek

This is the faulty line :

这是故障线路:

window.location=$(this).attr("http://google.com");

This doesn't make any sense, you're trying to change the location to the value of the attribute named "http://google.com" of your div.

这没有任何意义,您正在尝试将位置更改为 div 名为“http://google.com”的属性的值。

Just correct it like this :

就像这样纠正它:

$(".myBox").click(function(){
    window.location= "http://google.com";
     return false;
});

回答by Māris Kise?ovs

window.location="http://google.com";

回答by schellmax

$(".myBox").click(function(){
    window.location.href="http://google.com";
    return false;
});