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?
PHP中文网2017-05-18 11:01:41
1. The quotes are enclosed in commas
2.123456+"somestring"→"123456somestring"
3.elementId is a String type parameter, so add quotes
滿天的星座2017-05-18 11:01:41
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
漂亮男人2017-05-18 11:01:41
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
世界只因有你2017-05-18 11:01:41
First of all, the plus sign here is indeed used for string splicing
var repeat = "moveElement('"+ elementID +"',"+ final_x +","+ final_y +","+ interval +")";
The result of is
var repeat = "moveElement(elementID, final_x, final_y, interval)"
Just pass the string variable named repeat as a parameter to setTimeout, that is, after interval milliseconds, repeat will be executed
var repeat = "moveElement('"+ elementID +"',"+ final_x +","+ final_y +","+ interval +")";
movement = setTimeout(repeat, interval)
This is actually basically the same as
movement = setTimeout(function () {
moveElement(elementID, final_x, final_y, interval)
}, interval)
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?