开发者

question regarding the use of alert

i came upon this code while studying settimeout. the settimeout executes an alert 5 seconds after a button is clicked.

    <input type="button" name="clickMe" v开发者_运维百科alue="Click me and wait!" 
onclick="setTimeout('alert(\'Surprise!\')', 1000)">

however, i saw that the alert string inside has a format ive never seen before. the \ occurs before the ' Surprise! \'. what is its use?


This is the indented command: alert('Surprise!'). It contains two quotes.
In this case the command is passed as a string to setTimeout.
This string is delimited by quotes: 'string'.
Together this would look like 'alert('Surprise!')', which is invalid syntax, because it's parsed like this:

'alert('    // string
Surprise!   // nonsense
')'         // another string

So the quotes inside the string are escaped to signify "this is not the end of the string".

This is about the worst possible way to do this though. A better way would be to alternate the two available quote types:

'alert("Surprise!")'

This will mess up in this case though because it will confuse the HTML parser.

An even better way is to pass an anonymous function instead of a string:

setTimeout(function () { alert('Surprise!'); }, 1000)

An even betterer way is unobtrusive Javascript, in which you're not using HTML onclick attributes, but attach the Javascript to a DOM element programmatically:

<input type="button" name="clickMe" value="Click me and wait!" id="clicker">

<script type="text/javascript" charset="utf-8">
    document.getElementById('clicker').onclick = function () { 
        setTimeout(function () { alert('Surprise!'); }, 1000);
    };
</script>


It's an escape character. The backslash means that the quote is not the end of the string but instead part of it. It the backslash were not there, there would be a syntax error.

Dealing with escaped characters can get tricky when your Javascript is inline as an HTML attribute. I recommend reading about Unobtrusive Javascript for ways to avoid having to deal with this.


Those backslashes are there to escape the quotes within quotes. Normally one could write

alert('Surprise!');

but in this case this whole statement is to be passed as string. This would be syntax error

'alert('Surprise!');'

as we want the second and third quote as part of the string. So we escape it.

'alert(\'Surprise!\');'


this is used to scape the quots from the message. Otherwise it will take it as two string

one = 'alert('

second = ')'

And the Surprise! would be placed between those two strings.


It's an escape string. If you were to remove the backslashes, it would read:

..."setTimeout('alert('Surprise!')',1000)">

After the second ', the string would be complete, and your statement would now be an error because it's outside the quotation marks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜