javascript - 在没有内联事件的情况下调用 javascript 函数

标签 javascript jquery html css unobtrusive-javascript

我正在尝试使用用户喜欢的颜色突出显示单元格。用户将选择一个单元格并拖动鼠标以选择他们想要使用所选颜色着色的多个单元格。当用户在不使用内联事件处理程序的情况下单击并拖动鼠标时,如何触发位于单独文件中的 javascript 函数(我知道我必须将文件包含到 html 文件中,我已经这样做了)。

代码可以拖动和选择,但我想在用户单击并拖动单元格时调用此函数。在我使用 google.setOnLoadCallBack 调用此函数之前,但只会调用一次。我希望用户有多个选择。我希望我说得有道理。

HTML

<section id="importance">
   <label class="green">Green</label>
   <input type="radio" name="importance" value="green">

   <label class="yellow">Yellow</label>
   <input type="radio" name="importance" value="yellow">

   <label class="orange">Orange</label>
   <input type="radio" name="importance" value="orange">

   <label class="red">Red</label>
   <input type="radio" name="importance" value="red">
</section>

<table cellpadding="0" cellspacing="0" id="our_table">
  <tr>
   <td>a</td>
   <td>b</td>
   <td>c</td>
  </tr>
  <tr>
    <td>d</td>
    <td>e</td>
    <td>f</td>
  </tr>
  <tr>
    <td>g</td>
    <td>h</td>
    <td>i</td>
  </tr>
</table>

Javascript

function select_multiple() {
  var isMouseDown = false;
  // id for all the cells that were selected at the same time
  var colorGroupId = Math.floor(Math.random() * 1000);
  var highlight = find_importance_color();
  $("#our_table td")
    .mousedown(function () {
      isMouseDown = true;
      $(this).toggleClass(highlight);
      $(this).attr("data-highlightedId", colorGroupId);
      return false; // prevent text selection
  })
  .mouseover(function () {
    if (isMouseDown) {
      $(this).addClass(highlight);
    }
  });

  $("#our_table td")
    .mouseup(function (event) {
    isMouseDown = false;
    // time_importance(event);
  });
}

function find_importance_color() {
    return $('#importance input[name=importance]:checked').val();
}

CSS

.green {
  background-color: green;
}

.yellow {
  background-color: yellow;
}

.orange {
  background-color: orange;
}

.red {
  background-color: red;
}

table td {
  width:100px;
  height:100px;
  text-align:center;
  vertical-align:middle;
  background-color:#ccc;
  border:1px solid #fff;
}

最佳答案

将您的初始化函数传递给 jQuery 就绪处理程序:

$(document).ready(select_multiple);

jQuery 将在加载文档时调用它。

关于javascript - 在没有内联事件的情况下调用 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14492540/

相关文章:

php - 单击选择框中的项目,然后显示文本输入

javascript - JQuery GET 检索不需要的 HTML

javascript - 当我在 Django 中运行我的服务器时,我收到此请求错误,我一直在使用 Bootstrap

javascript - AJAX 不会覆盖已经加载的脚本?

html - 用于将文本居中放置在 div 中心的 css

javascript - JQuery IE <div> 不透明度问题

javascript - 用 javascript 替换损坏的 Twitter 图片?

javascript - 如何用JS获取索引?

jquery - jQtouch 使用 jQuery 而不是 Zepto

html - 如何在 ion-item 中并排对齐 ion-label 和 ion-img