html - question regarding the use of alert -
i came upon code while studying settimeout. settimeout executes alert 5 seconds after button clicked.
<input type="button" name="clickme" value="click me , wait!" onclick="settimeout('alert(\'surprise!\')', 1000)">
however, saw alert string inside has format ive never seen before. \ occurs before ' surprise! \'. use?
this indented command: alert('surprise!')
. contains 2 quotes.
in case command passed as string settimeout
.
string delimited quotes: 'string'
.
'alert('surprise!')'
, invalid syntax, because it's parsed this:
'alert(' // string surprise! // nonsense ')' // string
so quotes inside string escaped signify "this not end of string".
this worst possible way though. better way alternate 2 available quote types:
'alert("surprise!")'
this mess in case though because confuse html parser.
an better way pass anonymous function instead of string:
settimeout(function () { alert('surprise!'); }, 1000)
an betterer way unobtrusive javascript, in you're not using html onclick
attributes, attach javascript dom element programmatically:
<input type="button" name="clickme" value="click me , wait!" id="clicker"> <script type="text/javascript" charset="utf-8"> document.getelementbyid('clicker').onclick = function () { settimeout(function () { alert('surprise!'); }, 1000); }; </script>
Comments
Post a Comment