简体   繁体   English

让 div 成为 JavaScript 中的链接?

[英]Make a div a link in JavaScript?

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.我有一个盒子的布局,如果我的数据库中有一个值,我希望 PHP 将一些值回显到 JavaScript,并说如果这个盒子被占用,给这个 div (boxID) 与数据库相关的链接。 Only, there aren't going to be links on every div, as some won't exist in the database.只是,不会在每个 div 上都有链接,因为数据库中不存在一些链接。

I suppose the alternative to this is wrapping each div in a <a> tag and an if exists statement?我想这个的替代方法是将每个 div 包装在<a>标记和 if exists 语句中?

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'    
});

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';
});

在 html5 中你可以这样做:

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

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.由于 javascript 可能不是您想要的(等待额外的评论),这里有一个如何在纯 html/css 中执行此操作的示例。 An anchor tag that fills completely a div, making that div clickable.一个完全填充 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/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM