繁体   English   中英

将变量分配给div标签中的属性

[英]Assign variable to an attribute in div tag

我有以下代码。

我的要求是获取存储在myValue变量中的路径,并将其分配给div标签中的w3-include-html属性。

但是,我无法将myValue中显示的路径分配给div标记中的w3-include-html属性。

我尝试了HTML属性Javascript变量中提供的解决方案。 该链接讨论了img标签。 我为div标签尝试了相同的解决方案,但无法解决我的问题。

任何建议,将不胜感激。

<script>
    var myValue = "Tables/"+"FileName"+".html";
</script>   
<div id="openModal" class="modalDialog">
    <div>
        <a href="#close" title="Close" class="close">X</a>
        <div w3-include-html=myValue></div>
    </div>
</div>

您可以创建一个函数,在每次触发该函数时(通过setAttribute )将值分配给div:

 var myValue = 'Tables/' + 'FileName' + '.html'; var div = document.querySelector('div[w3-include-html]'); console.log('Value before function call: ' + div.getAttribute('w3-include-html')); insertMyValue(); console.log('Value after function call: ' + div.getAttribute('w3-include-html')); function insertMyValue() { div.setAttribute('w3-include-html', myValue); } 
 <div id="openModal" class="modalDialog"> <div> <a href="#close" title="Close" class="close">X</a> <div w3-include-html="myValue"></div> </div> </div> 

我通过添加id来解决此问题,如下所示:

<div id="openModal" class="modalDialog">
    <div>
        <a href="#close" title="Close" class="close">X</a>
        <div id="schema"></div>
    </div>
</div>

<script>
var myValue = "Tables/"+"Thing"+".html";
document.getElementById("schema").setAttribute('w3-include-html',myValue);
</script>   

我认为您可以添加一个间隔并检查值,它将自动检查更新。
一些代码示例:

 var myValue = "Tables/"+"FileName"+".html", element = document.querySelector('div[w3-include-html]'); function checkUpdate () { if (myValue !== element.getAttribute('w3-include-html')) { element.setAttribute('w3-include-html', myValue) console.log('updated to %s', myValue); } }; setInterval(checkUpdate, 100); setTimeout(() => myValue = "Test", 200); // only for example of update. 
 <div id="openModal" class="modalDialog"> <div> <a href="#close" title="Close" class="close">X</a> <div w3-include-html=myValue></div> </div> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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