简体   繁体   中英

Prevent Conversion of HTML Entities

I have a javascript function which takes a string as its parameter. This string is encoded (with %20 for spaces, %26 for ampersands, etc..).

function myFunction(theParam) {
       alert(theParam); // outputs &
}

// called by the following link
<a href="#" onclick='myFunction("%26")'>Do something</a>

How do I stop this behavior? I want myFunction to receive %26 as the parameter and not the ampersand......

Your example alerts %26 as expected for me. (And then falls through to navigating to # . Remember to return false from a click handler to stop the link being followed.)

You would get an ampersand if you did it in a javascript: link:

<a href="javascript:myFunction('%26')">Do something</a>

as javascript: URLs are still URLs and undergo normal URL-escaping rules. Of course, you should never use a javascript: URL anyway.

Better, assign from JavaScript itself so you don't have to worry about HTML-escaping issues either:

<a href="#" id="somethingdoer">Do something</a>

document.getElementById('somethingdoer').onclick= function() {
    myFunction('%26');
    return false;
};

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