【问题标题】:Assign variable to an attribute in div tag将变量分配给 div 标签中的属性
【发布时间】:2018-08-21 16:59:12
【问题描述】:

我有以下代码。

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

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

我尝试了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>

【问题讨论】:

  • 是否可以为所涉及的 div 分配一个类或 id?
  • 你的 html 语法有点不对劲。 myValue 应该用引号引起来。不是说这是你问题的根源,只是很高兴知道。
  • 确保您的浏览器支持此标签
  • @Jeroen Heier 分配 id 帮助我解决了这个问题。谢谢。

标签: javascript html variables attributes


【解决方案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>

【讨论】:

    【解决方案2】:

    我通过添加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>   
    

    【讨论】:

      【解决方案3】:

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

      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>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多