在锚标签内创建锚标签 [英] Creating anchor tag inside anchor tag

查看:95
本文介绍了在锚标签内创建锚标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的随机测试中,我看到了一个行为,我在其他锚标签中放置了一个锚标签。我制作了 jsfiddle

 < a class =groupPopper> 
< a class =name>内容< / A>

但是在开发者工具中,它显得不同: p>



我相信我们不能将一个锚标签放在另一个锚标签内,因为点击内部锚点会将点击事件吹到父锚标签,这应该是不允许的。



我的假设是否正确?

解决方案

正如@ j08691所描述的,嵌套在HTML语法中禁止元素。 HTML规范没有说明为什么;他们只是强调规则。在实践方面,浏览器在解析规则中有效地实施了这种限制,因此与其他许多问题不同,违反规范并不会工作。解析器将开放的 a 元素内的< a> 开始标签有效地视为隐式地在开始之前终止开放元素所以如果你写< a href = foo> foo< a href = bar>栏< / a> zap< / a> ,你不会得到嵌套的元素。浏览器会将其解析为< a href = foo> foo< / a> < a href = bar>栏< / a>



嵌套的 a 元素:可以实现它们以便点击foo或zap激活外部链接,点击bar激活内部链接。但我没有看到使用这种结构的理由,而HTML的设计者可能也没有看到其中一个,所以他们决定禁止它,从而简化事情。



(如果你真的想模拟嵌套链接,你可以使用普通链接作为外部链接,使用 span 元素作为内部链接,并使用合适的事件处理程序。 或者,您可以复制以下链接:< a href = foo> foo< / a>< a href = bar> bar< / a>< a href = foo> zap< / a> ; 。)


During my random testing I saw a behavior where I put an anchor tag inside another anchor tag. I made a jsfiddle.

<a class="groupPopper">
     <a class="name"> content</a>
</a>​

But in the developer tool it appears different:

I believe we cannot put an anchor tag inside another anchor tag as clicking on the inner anchor will bubble up the click event to the parent anchor tag which should not be allowed.

Is my assumption correct?

解决方案

As @j08691 describes, nested a elements are forbidden in HTML syntax. HTML specifications do not say why; they just emphasize the rule.

On the practical side, browsers effectively enforce this restriction in their parsing rules, so unlike in many other issues, violating the specs just won’t work. The parsers effectively treat an <a> start tag inside an open a element as implicitly terminating the open element before starting a new one.

So if you write <a href=foo>foo <a href=bar>bar</a> zap</a>, you won’t get nested elements. Browsers will parse it as <a href=foo>foo</a> <a href=bar>bar</a> zap, i.e. as two consecutive links followed by some plain text.

There is nothing inherently illogical with nested a elements: they could be implemented so that clicking on "foo" or "zap" activates the outer link, clicking on "bar" activates the inner link. But I don’t see a reason to use such a structure, and the designers of HTML probably didn’t see one either, so they decided to forbid it and thereby simplify things.

(If you really wanted to simulate nested links, you could use a normal link as the outer link and a span element with a suitable event handler as the inner "link". Alternatively, you could duplicate links: <a href=foo>foo</a> <a href=bar>bar</a> <a href=foo>zap</a>.)

这篇关于在锚标签内创建锚标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆