简体   繁体   中英

Multiple inline comments for html

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.

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/

<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.

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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