I am working on an asp.net mvc application. I need to know how to use global javascript variables inside html code. I know global variables are not an ideal solution to a problem but for my solution to work I need them.
I know about their declaration. Here is an example of how I want to use them. I want to use the global js variable to be already filled in at the input.
var title; function foo(b) { title = b; };
<input type="text" value=title readonly>
Any help will be appreciated. Thanks.
var title; function foo(b) { document.getElementById("title").value = b; }; foo("irin")
<input type="text" id="title" readonly>
Use the setProperty
function of the style
object of any HTMLElement
object
"use strict"; // Note the double quotation '" and "' // I won't work without, if you want to use the value // with CSS content rule const title = '"My title"'; document.getElementById('title').style.setProperty('--title', title);
div { padding: 5px; border: 1px solid gold; } div:before { content: var(--title, 'not set'); }
<div id="title"></div>
In the above example I used a [CSS custom Property][1]
, but you could do without
"use strict"; const title = '"My title"'; const style = document.createElement('style'); style.textContent = `#title:before { content: ${title}; }`; document.head.append(style);
div { padding: 5px; border: 1px solid gold; }
<div id="title"></div>
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.