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

时间:2018-08-21 16:59:12

标签: javascript html variables attributes

我有以下代码。

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

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

我尝试了Javascript variables in HTML attributes中提出的解决方案。该链接讨论了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>

3 个答案:

答案 0 :(得分:1)

您可以创建一个函数,在每次触发该函数时将其值(通过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>

答案 1 :(得分:1)

我通过添加如下所示的ID解决了这个问题:

ps -aux | grep python3

答案 2 :(得分:0)

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

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>

相关问题