最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - JavaScript: Single quote ' causes error - Stack Overflow

programmeradmin4浏览0评论

I have a string with a ' inside it:

<a href="#" onclick="if (confirm('... &#039; ...')) { document.exampleFormName.submit(); }">example link text</a>

Unfortunately this does not seem to work. Firebug says "SyntaxError: missing ) after argument list" and you can see that the HTML entity has already been replaced by '.

What can I do to avoid this problem?

I have a string with a ' inside it:

<a href="#" onclick="if (confirm('... &#039; ...')) { document.exampleFormName.submit(); }">example link text</a>

Unfortunately this does not seem to work. Firebug says "SyntaxError: missing ) after argument list" and you can see that the HTML entity has already been replaced by '.

What can I do to avoid this problem?

Share Improve this question edited Mar 30, 2015 at 13:25 jcubic 66.8k58 gold badges249 silver badges455 bronze badges asked Mar 30, 2015 at 13:17 chris342423chris342423 4511 gold badge8 silver badges22 bronze badges 5
  • Try this.. <a href="#" onclick='if (confirm("... &#039; ...")) { document.exampleFormName.submit(); }'>example link text</a> – Rakesh_Kumar Commented Mar 30, 2015 at 13:19
  • where is the "string with a ' inside it" – atmd Commented Mar 30, 2015 at 13:19
  • 1 Well, of course it does, &#039; is a single quote, making it an entity doesn't help at all, you have to escape it, as in \' – adeneo Commented Mar 30, 2015 at 13:20
  • 1 Use addEventListener and forget the onclick attribute. – Ram Commented Mar 30, 2015 at 13:20
  • jsfiddle/z0x0swt8 – adeneo Commented Mar 30, 2015 at 13:20
Add a ment  | 

3 Answers 3

Reset to default 5

It's not beautiful to write like that XD

<a href="#" onclick="if (confirm('... &#039; ...')) { document.exampleFormName.submit(); }">example link text</a>

It's better to use a function

<script>
  function foo() {
    if (confirm("...' ...")) { document.exampleFormName.submit(); }
    return false; // disable the link
  }
</script>
<a href='#' onclick='return foo()'>example link text</a>

but maybe that just me..

You should escape quotes. not use html entities. In a '' string you use \' to escape single quotes.

Read more about escape characters: https://mathiasbynens.be/notes/javascript-escapes

    
    <a href="#" onclick="if (confirm('... \' ...')) { document.exampleFormName.submit(); }">example link text</a>

Try this

<a href='#' onclick='if (confirm("... &#039; ...")) 
{ 
  document.exampleFormName.submit(); 
}'> example link text
</a>

Because "#039" stands for single quote so ('...'...') in your previous code would fail because of this reason

发布评论

评论列表(0)

  1. 暂无评论