There is something I don’t understand very well. This time I saw a piece of code that explains the problem very well:
function moveElement (elementID, final_x, final_y, interval) {
var elem = document.getElementById(elementID);
var xpos = parseInt(elem.style.left);
var ypos = parseInt(elem.style.top);
......
var repeat = "moveElement('"+ elementID +"',"+ final_x +","+ final_y +","+ interval +")";
movement = setTimeout(repeat, interval)
}
I only have one question:
var repeat = "moveElement('"+ elementID +"',"+ final_x +","+ final_y +","+ interval +")";
In this paragraph, elementID
, final_x
, final_y
, interval
are the four parameters passed in, except for the first One is a string, and the last three are numbers.
The first thing I don't understand is why these parameters need to be added with quotes . The second thing I don't understand is what role the plus sign has. Another question is why does a string like elementID
contain double quotes? Under what circumstances is this necessary?
Generally I think the plus sign is suitable for string splicing, but this is obviously not the case here. A pair of quotation marks is an independent space. What is the meaning of the plus sign wrapped in it?
1. The quotes are enclosed in commas
2.123456+"somestring"→"123456somestring"
3.elementId is a String type parameter, so add quotes
The variable is finally converted to a string! Numbers + quotation marks change characters. If the parameter you need is a string instead of a number
The string here is equivalent to the usage of eval in setTimeout, which refers to the code string you want to execute after delay milliseconds
First of all, the plus sign here is indeed used for string splicing
The result ofis
Just pass the string variable named repeat as a parameter to setTimeout, that is, after interval milliseconds, repeat will be executed
This is actually basically the same as
This should be easier to understand, right?
However, there are still differences between these two methods. Generally, the method mentioned by the questioner is not recommended. For details, see window.setTimeout, Running string as function in javascript setTimeout?