How do I escape a string inside JavaScript code inside an onClick handler?

前端 未结 13 843
半阙折子戏
半阙折子戏 2020-11-28 03:44

Maybe I\'m just thinking about this too hard, but I\'m having a problem figuring out what escaping to use on a string in some JavaScript code inside a link\'s onClick handle

相关标签:
13条回答
  • 2020-11-28 04:33

    First, it would be simpler if the onclick handler was set this way:

    <a id="someLinkId"href="#">Select</a>
    <script type="text/javascript">
      document.getElementById("someLinkId").onClick = 
       function() {
          SelectSurveyItem('<%itemid%>', '<%itemname%>'); return false;
        };
    
    </script>
    

    Then itemid and itemname need to be escaped for JavaScript (that is, " becomes \", etc.).

    If you are using Java on the server side, you might take a look at the class StringEscapeUtils from jakarta's common-lang. Otherwise, it should not take too long to write your own 'escapeJavascript' method.

    0 讨论(0)
提交回复
热议问题