简体   繁体   中英

javascript with() function won't work in Opera, Chrome or Brave

I'm inherited an HTML form that uses the js with() function:

with (document.images.myImage.style) {
    left = x + "px";
    top  = y + "px";
    visibility = "visible";     
}

This code "moves" an image on a graph based on the left/top settings.

Movement is normal in Firefox, IE and Edge, but not in the others...I'm not familiar enough with js to recode so it works in all the browsers.

Does anyone have recomendations on how to recode this?

with(expression) adds the expression to the scope search chain to the block inside the with statement.

The most direct replacement I can think of would be assigning a variable to document.images.myImage.style and prepending that to each line. So...

var style = document.images.myImage.style; 
style.left = x + "px"; 
style.top = y + "px"; 
style.visibility = "visible"; 

with is a statement , like a for loop, not a function. What with does is allow you to reference properties on an object without typing out the objects name every time.

with(myObj) {
  x = y;
}

is the same as

myObj.x = myObj.y;

But it's not allowed in strict mode nor should it be used in non-strict mode (tends to be the source of a lot of bugs). So to translate any with code, just prefix any values coming from the object with the actual object.

document.images.myImage.style.left = x + 'px';
document.images.myImage.style.top = y + 'px';
document.images.myImage.style.visibility = 'visible';

Thank you for all the information.

What I ended up doing is as "Mike C" suggested and replaced the with() statement using "document.images.style.xxx=" statements.

So far it works find in all the browsers I could find.

Again, the forum is amazing at letting you on to what others know/have discovered...Thanks again for all your help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM