【问题标题】:InnerHTML not working [duplicate]InnerHTML 不起作用[重复]
【发布时间】:2016-03-25 14:22:24
【问题描述】:

我知道在herehere 之前也有人问过类似的问题。但是这些与我的情况并不完全相似,因为他们在尝试更新 div 元素的 HTML 时尝试更改输入框的值。我的问题是我在 HTML 页面的顶部调用了一个 JS 函数,该函数旨在更新页面上 div 元素之一的 innerHTML。由于某种原因,这不起作用。根据this question 的回答,我知道这可能是因为我什至在页面完全加载之前就尝试访问 div。为了解决这个问题,我尝试从主题 div 的 onload() 事件中调用该函数。但是,即使这样也不起作用。

function wotd() {
  $('#wotd').HTML("<strong>test</strong>");
  alert($('#wotd').text());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
  //wotd();
</script>

<div class="col col-md-4">
  <!-- WOTD panel -->
  <div class="panel panel-default panel-box card-effect">
    <div class="panel-heading panel-title">Word of the Day</div>
    <div id="wotd" class="panel-body panel-text" onload="wotd();">
      Word of the day not currently available.
    </div>
  </div>
</div>

【问题讨论】:

  • div 没有onload 事件,对于初学者来说。

标签: javascript jquery html


【解决方案1】:

innerHTMLjavasript 属性。您应该在jquery 中使用html() 来替换元素的内容。而且div 没有onload 事件。您应该在 document readybody load 上执行此操作,如下所示。

function wotd() {
    $('#wotd').html("<strong>test</strong>");
    alert($('#wotd').text());
}

wotd();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col col-md-4">
  <div class="panel panel-default panel-box card-effect">
    <div class="panel-heading panel-title">Word of the Day</div>
    <div id="wotd" class="panel-body panel-text" onload="wotd();">
      Word of the day not currently available.
    </div>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2017-05-03
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 2015-02-19
    • 2019-09-23
    • 1970-01-01
    相关资源
    最近更新 更多