简体   繁体   中英

Reference to a javascript variable in an HTML tag

I am trying to "link" a tag value to a javascript variable (and ideally to a function, but well a variable is a good start), by reference. I know I can do a myDom.value = myVar but then if the value of myVar change the tag will not be modified.

Is it possible to do this (not using events, because it would be so heavy)?

Thank you :)

No.

You can fake references by assigning objects to things, but only if the property you assign the object to is expecting an object and knows to pull data out of it instead of stringifying it and using it directly.

You could use a closure function around the variable. So instead of attaching the value, you attach a function which will return the variable:

myDom.valueAccessor = function(){ return value }

After this you can access the result as:

myDom.valueAccessor()

This will track the value in value as it changes. Obviously you could choose a snappier name for your function. This seems to work for me in Firefox.

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