简体   繁体   中英

Can you use HTML entities inside inline JavaScript?

I have just been doing some work on a website that I haven't built, and noticed that there is some JavaScript being used inline on an onClick attribute.

The puzzling thing is that the JavaScript looks like it shouldn't work, but it isn't erroring. The reason I believe it shouldn't work is because instead of quote marks ' the HTML entity code is used instead: ' .

Exact code below:

onClick="ga('send', 'event', { eventCategory: 'Place', eventAction: 'Book', eventLabel: 'Open'});"

I'll be changing this as a matter of course, but is this, technically, acceptable JS?

This piece of Javascript is embedded into HTML. The browser will first read and process the HTML, which includes decoding any entities. It then discovers that parts of this HTML are Javascript, so it hands the (by this time HTML-decoded) Javascript off to its Javascript interpreter to interpret.

The entities are and should be encoded because they're embedded inside of HTML, so you must conform to HTML's syntax first. It's the old quotes-inside-quotes problem. HTML solves it with HTML entities.

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