【问题标题】:Modal with Changing Content改变内容的模态
【发布时间】:2017-08-15 12:49:14
【问题描述】:

我正在一个名为 modal.html 的文件中创建一个模态,而要填充该模态的内容来自一个外部 JS 文件。内容是一个名为 one.js 的 JS 文件中以下函数返回的字符串:

function current()
{
  if(selection === 0 && yesResources[questionsCounter] != null)
  {
    return yesResources[questionsCounter];
  }
  else if(selection === 1 && noResources[questionsCounter] != null)
  {
  return noResources[questionsCounter];
  }
  else
  {
    return 'You are on the right track!';
  }
}

为modal编写的HTML代码如下:

<!-- The Modal -->
<div id="myModal" class="modal">

    <!-- Modal content -->
    <div class="modal-content">
        <div class="modal-header">
           <span class="close">&times;</span>
           <h2>Resources</h2>
        </div>
    <div class="modal-body">
        <p>Test</p>
        <p id='modalContent'></p>
    </div>
    <div class="modal-footer">
        <h3>Living Progress</h3>
    </div>
  </div>
</div>

我想调用 current() 函数来填充 id 为“modalContent”的段落空间。我尝试使用 document.getElementById("modalContent").innerHTML = current(), document.getElementById("modalContent").textContent = current(),在段落标签之间调用函数等。还有其他建议吗?谢谢。

【问题讨论】:

    标签: javascript html modal-dialog


    【解决方案1】:

    你在输入 document.getElementById() 时忘记了 id 名称,我建议你使用 document.querySelector('#modalContent'),因为这样也可以应用于选择类名或标记名。

    【讨论】:

      【解决方案2】:

      你应该使用document.getElementById("modalContent").textContent = current();而不是document.getElementById.textContent = current()(你忘了在getElementById之后指向id)。

      【讨论】:

      • 我确实包含了它,但在上面的帖子中犯了一个错误,所以我在那里修复了它。当我按照你说的那样做时,模态完全停止出现,你知道为什么会这样吗?记住 current() 函数来自外部 JS 文件
      【解决方案3】:

      你应该使用:

      document.getElementById("modalContent").innerHTML = "Your content here";
      

      这会解决你的问题。

      【讨论】:

      • 大卫,我使用了它,不同之处在于等号右侧的文本在我的情况下被替换为 current() 。它似乎使模态完全停止显示......你知道为什么吗?
      • yesResources 或 noResources 返回的内容可能与字符串不同,您能否向我们提供此内容以便我们考虑抛出它?
      • yesResources 和 noResources 包含字符串或 null 的元素。是因为空元素吗?
      • 不是因为null。我做了一些故障排除,我调用的函数没有定义,这意味着 HTML 文件无法识别该函数。这是为什么呢?
      • 你的项目中导入了one.js?就像这样 但是你应该为你的 js 文件放置正确的目录
      【解决方案4】:

      我检查了你的javascript代码,样式不好,条件太长。我修改了代码如下。

      var e = function(sel) {
          return document.querySelector(sel)
      }
      
      function current() {
          var yR = yesResources[questionsCounter]
          var nR = noResources[questionsCounter]
      
          if (selection === 0 && yR != null) {
              return yR;
          } else if (selection === 1 && nR != null) {
              return nR
          } else {
              return 'You are on the right track!'
          }
      }
      
      e('#modalContent').innerHTML = '<h1>hi is here</h1>'

      【讨论】:

      • 它似乎不起作用。当我尝试这个时,模式根本没有出现。
      • 没关系,模态仍然有效,但来自 current() 函数的数据没有被放入模态
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 2015-09-24
      • 2017-11-17
      • 1970-01-01
      • 2019-05-25
      相关资源
      最近更新 更多