将 DIV 包裹在 Anchor 标签内或以其他方式 [英] Wrapping DIV inside Anchor tag or otherwise

查看:32
本文介绍了将 DIV 包裹在 Anchor 标签内或以其他方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个可点击的复杂 div 元素结构,它链接到另一个页面,如下所示.这是目前正在通过点击实现的事情.单击时(css :active 状态)更改 <a> 标签内的背景颜色并重定向到其他页面.

我想知道与使用 div 包装它并使用 JavaScript 管理链接重定向和点击时背景颜色更改相比,这是否符合 HTML5 验证或被视为最佳实践.

对我来说,第一种方法似乎更简洁、更直接.

我相信这是许多 Web 开发人员面临的共同问题,但我不确定是否有针对此的现有最佳实践解决方案.

1) 保持原样

<div><!-- 复杂的布局-->

</a>

2) 省略 标签并在点击事件期间管理背景颜色并使用 JavaScript 重定向

HTML5,您可以DIV 包裹在 中A

<div><!-- 复杂的布局-没有锚点或按钮-->

</a>

仅当 中您没有另一个 或 Form-action 元素,如

但是内联 JavaScript 是糟糕的设计,因为难以维护和调试,所以最好将它放在您的脚本文件中.

Suppose I have a clickable complex div element structure which links to another page as follows. This is the thing that is being achieved currently on click. On click (css :active state) change the background color inside <a> tag and redirect to other page.

I am wondering whether this conforms to HTML5 validation or consider as a best practice compared to wrapping it with a div and using JavaScript to manage the link redirect and background color change on click.

To me, the first approach seems to be much cleaner and straight forward.

I believe this is a common issue face by a lot of web developers but I am not sure whether there is an existing best practice solution for this.

1) Maintain as this

<a href="page1.html">
    <div>
        <!-- complex layout -->
    </div>
</a>

2) Omit the <a> tag and manage background color during click event and redirect using JavaScript

<div id="#redirectLink" data-link="page1.html">
    <!-- complex layout -->
</div>

解决方案

HTML5, you can wrap a DIV inside an A anchor

<a href="page1.html">
    <div>
        <!-- complex layout - WITHOUT ANCHORS OR BUTTONS -->
    </div>
</a>

only if inside <!-- complex layout --> you don't have another <a> or Form-action elements like <button> etc.

Otherwise you can do:

<div id="#redirectLink" data-link="page1.html">
    <!-- complex layout -->
</div>

<script>
document.querySelectorAll("[data-link]").forEach( el =>  {
   el.addEventListener("click", () => window.location.href = el.dataset.link);
});
</script>

or simply:

<div id="#redirectLink" onclick="window.location.href='page1.html';">
    <!-- complex layout -->
</div>

but inline JavaScript is bad design since hard to maintain and debug, so prefer having it in your script files.

这篇关于将 DIV 包裹在 Anchor 标签内或以其他方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆