在 JavaScript 中将 div 设为链接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20893280/
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-10-27 19:33:57  来源:igfitidea点击:

Make a div a link in JavaScript?

javascriptcss

提问by BN83

Everything I've searched for has shown about making a full div clickable, what I'm wondering is, is it possible to make a div in to a clickable link using just JavaScript and the div ID?

我搜索的所有内容都显示了如何使完整的 div 可点击,我想知道的是,是否可以仅使用 JavaScript 和 div ID 将 div 制作成可点击的链接?

I have a layout of boxes and if a value in my database, I want PHP to echo some values in to JavaScript and say if this box is taken, give this div (boxID) the link that relates to it from the database. Only, there aren't going to be links on every div, as some won't exist in the database.

我有一个盒子的布局,如果我的数据库中有一个值,我希望 PHP 将一些值回显到 JavaScript 中,并说如果这个盒子被占用,给这个 div (boxID) 从数据库中与它相关的链接。只是,不会在每个 div 上都有链接,因为有些在数据库中不存在。

I suppose the alternative to this is wrapping each div in a <a>tag and an if exists statement?

我想替代方案是将每个 div 包装在一个<a>标签和一个 if exists 语句中?

回答by Astralian

In pure JS:

在纯 JS 中:

document.getElementById('your-div').addEventListener('click', function() {
    location.href = 'http://your-url.com'
}, false);

By jQuery

通过 jQuery

$('#your-div').on('click', function() {
    location.href = 'http://your-url.com'    
});

回答by Damien Black

you can easily make it so that when you click your div you go to another page, like this (using jQuery)

你可以很容易地做到这一点,当你点击你的 div 时,你会转到另一个页面,就像这样(使用 jQuery)

$('#myId').click(function () {
    window.location = 'newurl.php';
});

回答by Spencer Wieczorek

In html5 you can just do:

在 html5 中,你可以这样做:

<a href="link"><div>test</div></a>

回答by Francisco Presencia

This solution is for html <= 4. For html5, please read @Spencer solution.

此解决方案适用于 html <= 4。对于 html5,请阅读 @Spencer 解决方案。

Since the javascript is probably not what you want (waiting for extra comments), here's a example of how to do this in pure html/css. An anchor tag that fills completely a div, makingthat div clickable.

由于 javascript 可能不是您想要的(等待额外的评论),这里有一个示例,说明如何在纯 html/css 中执行此操作。一个完全填充 div 的锚标记,使该 div 可点击。

html:

html:

<div>
  <a href = "http://whatever.com/">
  </a>
</div>

css:

css:

div {
    width: 200px;
    height: 200px;
    position: relative;
    background-color: red;
}
a {
    display: block;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background-color: rgba(0, 255, 0, 0.5);
}

Demo in jsfiddle (background-color added for demonstration purposes):

jsfiddle 中的演示(为了演示目的添加了背景色):

http://jsfiddle.net/Gx3f5/

http://jsfiddle.net/Gx3f5/