Multiple inline comments for html

2019-09-07 23:20发布

I am trying to comment the following html so that it shouldn't go to hyperlink.

<a href="<!--http://www.google.com=-->" target="_blank" onclick="javascript:alert('Navigation Prevented')">CLICK HERE FOR GOOGLE</a>

I am unable to comment target="_blank". if I do so it doesn't work and it displays javascript on page as well.

How do I have the page display alert as well as stop opening the page in new tab. I want the effect of target="_blank" to be cancelled.

Can't we have multiple comments inline for html.

4条回答
我想做一个坏孩纸
2楼-- · 2019-09-07 23:38

You can't have HTML comments inside an HTML tag, as the comment is a tag itself.

You can return false from the event handler to keep the browser from following the link:

<a href="http://www.google.com" target="_blank" onclick="javascript:alert('Navigation Prevented');return false;">CLICK HERE FOR GOOGLE</a>
查看更多
beautiful°
3楼-- · 2019-09-07 23:39
<a href="google.com" target="_blank" onclick="javascript:alert('Navigation Prevented');return false;">CLICK HERE FOR GOOGLE</a>

The important part of this is the return false; on the onclick attribute. This instructs the browser to immediately cancel this link after clicking. So what will happen is the javascript will be executed, but the link will not be followed.

查看更多
闹够了就滚
4楼-- · 2019-09-07 23:41

You cannot have comment tags inside the attribute value of an element.

Instead of commenting, you can do this way, by adding a return false;. This prevents the browser from following the link:

<a href="http://www.google.com" target="_blank"
   onclick="javascript:alert('Navigation Prevented'); return false;">CLICK HERE FOR GOOGLE</a>

Fiddle: http://jsfiddle.net/rBmjs/

查看更多
ら.Afraid
5楼-- · 2019-09-07 23:46

After seeing other users say that comments can't be included within element attributes, I started to wonder why. Certainly it's a bad practice, but why shouldn't it work?

I checked the specs for HTML5 comments and HTML4.01 comments, and the answer was in the 4.01 spec:

Note that comments are markup

The <! part of a comment merely opens a declaration, and > closes it. It's the -- string that identifies the declaration as a comment. This becomes obvious when comparing comment syntax to doctype declarations and CDATA sections.

Because you can't put declarations inside attribute values (I wasn't able to find this explicitly stated in the spec, but it seems obvious), comments can't be included in attribute values.

Interestingly, the HTML5 comments section doesn't mention the 'comments are markup' note. However, I feel sure the same rules still hold.

If any of this is wrong, please feel free to post corrections.

查看更多
登录 后发表回答