Chang Rik
Chang Rik

Reputation: 27

What does "(\'' + element + '\')" mean?

function expand(element) {
    var target = document.getElementById(element);
    var h = target.offsetHeight;
    var sh = target.scrollHeight;
    var loopTimer = setTimeout('expand(\'' + element + '\')', 10);
    if (h < sh) {
        h += 1;
    } else {
        clearTimeout(loopTimer);
        alert("伸縮完成");
    }
    target.style.height = h + "px"
}

Upvotes: 0

Views: 68

Answers (3)

Christopher D&#237;az
Christopher D&#237;az

Reputation: 346

In Javascript you can pass as the first parameter of the function a string, this string is evaluated as if you use eval(). That code is like if you call the function expand("something") every 10 milliseconds.

Upvotes: -1

jleach
jleach

Reputation: 7792

\' is an escape character for ', so what this is doing is building a string that can be consumed as a function, which contains a parameter, which is wrapped in single quotes...

'expand(\''

The above portion "opens" the string, applies expand( as a literal, then an escaped ', followed by one more ' to close that portion of the string. So, the return on that is:

expand('

Next, they concatenate the value of element variable:

'expand(\'' + element

The string now contains:

expand('elementVariableValue

Next up is to open another literal string, add in another single quote (escaped), followed by the closing parenthese:

'\')'

this is evaluated to:

')

put it all together and you get:

expand('elementVariableValue')

(which is finally interpreted as a function for the timeout).

Now, with JavaScript, you can use both " and ' for string delimiters, so much easier might have been:

setTimeout("expand('" + element + "')", 10);

Upvotes: 3

Horsing
Horsing

Reputation: 1100

Code in your example is a recursive call. It's a timer and the callback is expand(element). Understand this, you can easy understand that var loopTimer = setTimeout('expand(\'' + element + '\')', 10); means another call to expand(element). However, function expand need a string parameter, so \'' + element + '\' it is. Finally, if element here equals to scaleid, we finally get expand('scaleid'), it is obviously another call to expand(). Cause it is in string, so \' is needed to escape it.

Upvotes: 1

Related Questions