当我的8x8表中的任何链接被单击时,我如何运行一个函数



我有一个8x8的表格,用于座位预订网站(这是一个统一的任务)。当他们中的任何一个被点击,我想要一个javascript函数运行。我知道如何做到这一点,当你有一个单一的链接,即getElementById()和onclick,但我想要的是一种方法,将相同的功能应用到所有的链接,而不做64唯一的id和onclick行…这是真的吗?如果我所说的没有任何意义,我很高兴澄清任何事情,希望我能在截止日期之前把它整理好!

试试这个:

var links = document.getElementById("grid").getElementsByTagName("a");  //get every anchor tag in #grid div
    for(var i = 0; i < links.length; i++) {     //loop through every anchor tag tag
        var link = links[i];
        link.onclick = function(e) {    //add an event handler to each anchor tag
            e.preventDefault();         //prevent the default action from happening, e.g. the href
            alert("Link clicked!");     //do whatever
        }
    }

假设你的href在一个名为"grid"的div中,这将为它们中的每个添加一个事件处理程序,无论它们在link.onclick = function(){代码内做什么

http://jsfiddle.net/jofish999/v6kgsmqk/

首先,你必须学习javascript。我向您解释一小段jquery代码(您必须添加jquery库才能工作)。

HTML

我们可以添加data-*自定义属性来标识X轴和Y轴。

   <div class="square" data-cell-x="0" data-cell-y="0"></div>
   <div class="square" data-cell-x="1" data-cell-y="0"></div>
   <div class="square" data-cell-x="2" data-cell-y="0"></div>
   <div class="square" data-cell-x="3" data-cell-y="0"></div>
   <div class="square" data-cell-x="4" data-cell-y="0"></div>
   <div class="square" data-cell-x="5" data-cell-y="0"></div>
   <div class="square" data-cell-x="0" data-cell-y="0"></div>
   <div class="square" data-cell-x="1" data-cell-y="1"></div>
   <div class="square" data-cell-x="2" data-cell-y="2"></div>
   <div class="square" data-cell-x="3" data-cell-y="3"></div>
   <div class="square" data-cell-x="4" data-cell-y="4"></div>
   <div class="square" data-cell-x="5" data-cell-y="5"></div>
Javascript

现在,在jquery的帮助下,我们可以添加几行来处理所有的onclick:

 $('.square').each(function() {
       // on each square we can:
      $(this).on('click' , function(e) {
          // prevent default action behaviour (i.e. a link)
          e.preventDefault();
          //catch dataset (data-* attributes)
          var ds = $(this).dataset();
          // alert with result
          alert("X: "+ ds.cellX+" ; Y: "+ds.cellY);
      });
 });

祝你好运!

最新更新