javascript - 无法让 javascript 在 jsfiddle 中以 HTML 形式工作

标签 javascript html css forms jsfiddle

我正在整理一个 html 表单,我可以在其中将用户添加到电子邮件分发列表。我试图在 jfiddle 上模拟这个,但由于某种原因 javascript 无法工作。当我将以下代码保存在 html 页面中并在浏览器中尝试时,它工作正常。我的问题是我在 jsfiddle 中做错了什么并且 javascript 函数不起作用。谢谢!

不工作的jsfiddle在这里:MyFiddleExample

My Form

function onAddClicked() {
  var userList = document.getElementById("UserList");
  var distributionList = document.getElementById("DistributionList");

  var newMember = document.createElement('option');
  newMember.value = userList.options[userList.selectedIndex].value;
  newMember.innerHTML = userList.options[userList.selectedIndex].text;

  distributionList.appendChild(newMember);
}
<form>

  <div class="form-row">
    <div class="form-group col-md-5">
      <label for="UserList">Available Users:</label>
      <select class="form-control" name="UserList" size=10 id="UserList">
        <option value="UserA">User A</option>
        <option value="UserB">User B</option>
        <option value="UserC">User C</option>
        <option value="UserD">User D</option>
      </select>
    </div>

    <div class="col-md-2">
      <button type="button" onclick="onAddClicked()" class="btn btn-success btn-block" style="margin-top:33px">Add &gt;&gt;</button>
      <button type="button" class="btn btn-danger btn-block" style="margin-top:33px">&lt;&lt; Remove</button>
    </div>

    <div class="form-group col-md-5">
      <label for="DistributionList">Distribution List Members:</label>
      <select class="form-control" name="DistributionList" size=10 id="DistributionList">
      </select>
    </div>
  </div>
</form>

最佳答案

该问题特定于 JSFiddle。您需要将负载类型更改为无换行 - <body> 的底部.

当在 DOM 加载上使用时,该函数不会成为全局函数,因此您不能直接从 HTML 调用它。如果它是全局的 - 就像使用 no-wrap 时 - 它可以工作。

关于javascript - 无法让 javascript 在 jsfiddle 中以 HTML 形式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53867786/

相关文章:

javascript - 为什么脚本类型前面有 "text/"?

javascript - 随机化 float CSS

javascript - 为什么 clearInterval 在此代码中不起作用?

javascript - Google Drive API 在上传时返回 404

javascript - ErrorAccessDenied 使用 Microsoft Graph 删除附件

javascript - 从 JsTree 选择填充文本字段

javascript - 替代显示 :none using CSS and Javascript

javascript - jQuery - 使用 .hover 而不是 .click

HTML 背景颜色泄漏

javascript - onCollapse 将父节点设置为选定节点,如果子节点/孙节点已被选中(bootstrap treeView)