外部JS文件没有触发

问题描述 投票:0回答:2

当我用onclick事件触发它时,我无法触发外部JS文件。

JS文件与html文件位于同一目录中。

这是html:

<head>
  <script src='request.js'></script>
</head>

<h1>Requests</h1>

<table>
  <thead>
    <tr>
      <th>Artist</th>
      <th>Title</th>
      <th>Votecount</th>
      <th>Vote for Song</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @requests.each do |request| %>
      <tr>
        <td><%= request.artist %></td>
        <td><%= request.title %></td>
        <td class="voteCount"><%= request.voteCount %></td>
        <td><button onclick="upVote()">Vote</button></td>
      </tr>
    <% end %>
  </tbody>
</table>

这是我的JS文件中的内容:

function upVote() {
        alert("firing trigger");
        var count = document.getElementsByClassName("voteCount")[0].innerHTML;
        count = parseInt(count);
        count = count + 1;
        count = count.toString();
        document.getElementsByClassName("voteCount")[0].innerHTML = count;
  }

这是我的目录列表:Directories

javascript html erb jbuilder
2个回答
0
投票

使用Rails,有一个assets文件夹,需要存储外部JS文件。

app/assets/javascripts

-1
投票

发生这种情况是因为代码是在生成DOM之前执行的。尝试将<script src='request.js'></script>移动到<body>的末尾

<body>

<h1>Requests</h1>

<table>
  ...
  ...
</table>
<script src='request.js'></script>
</body>
© www.soinside.com 2019 - 2024. All rights reserved.