简体   繁体   English

为 html 元素赋值并读取它

[英]Assigning values to html elements and reading it

I'm trying to make tic-tac-toe game, basing just on html, CSS and pure js.我正在尝试制作井字游戏,仅基于 html、CSS 和纯 js。 I have already base of game (there is one bug), but I have problem to detect once someone wins.我已经有了游戏基础(有一个错误),但是一旦有人获胜,我就很难检测到。 I've decided to use MagicSquare algorithm, but I don't have idea how to attach value to each td element.我决定使用MagicSquare算法,但我不知道如何为每个 td 元素附加值。 Here you can find, what I have at this moment.在这里你可以找到,我此刻所拥有的。 I'm trying to make something like player += Number(target.value);我正在尝试制作类似player += Number(target.value);东西player += Number(target.value); and once one of the players collect 15, then I stop game and display message.一旦其中一名玩家收集到 15,我就会停止游戏并显示消息。 Of course, this doesn't work now, so can you advise me some good idea how to assign values with td elements and later read it via js, once player generate click event?当然,这现在不起作用,所以你能告诉我一些好主意如何用 td 元素分配值,然后在播放器生成点击事件后通过 js 读取它吗?

index.html索引.html

<table class="gameArea" onclick="myFunction(event)">
     <tbody>
         <tr>
             <td value=4></td>
             <td value="9"></td>
             <td value="2"></td>
         </tr>
         <tr>
             <td value="3"></td>
             <td value="5"></td>
             <td value="7"></td>
         </tr>
         <tr>
             <td value="8"></td>
             <td value="1"></td>
             <td value="6"></td>
         </tr>
     </tbody>
</table>

script.js脚本.js

  var player1 = 0,
      player2 = 0,
      round = 0;

function myFunction(event) {
    var target = event.target;
    //target.className += "x";

    if(hasClass(target, "x") || hasClass(target, "y") ){
      alert("Taken");
      return;
    }

    if(round === 1){
      target.className += "x";
      player1 += Number(target.value);
      round = 0;
      console.log(target.value);
    } else {
      target.className += "y";
      round = 1;
      player2 += Number(target.value);
      console.log("Player 2: " + player2);
    }

    console.log(round);
  }

  function hasClass( elem, klass ) {
   return (" " + elem.className + " " ).indexOf( " "+klass+" " ) > -1;
}

Change your HTML to use data attributes, like so:更改您的 HTML 以使用数据属性,如下所示:

<td data-value="3"></td>

You can then read the value, like so:然后您可以读取该值,如下所示:

player1 += parseInt(target.dataset.value, 10);

More info on MDN here .关于 MDN 的更多信息在这里

In your specific case, you already have the information attached to the element: You have a class, x or y , which tells you who's marked that square.在您的特定情况下,您已经拥有附加到元素的信息:您有一个类xy ,它告诉您是谁标记了那个方块。 You can simply use that.你可以简单地使用它。

In the general case, there are three common approaches:在一般情况下,有三种常见的方法:

  1. A separate data cache, keyed by an element's id or other unique identifier associated with the element.一个单独的数据缓存,由元素的id或与元素关联的其他唯一标识符键控。 The idea here is that you give elements unique IDs, and use those IDs as keys into an object that stores the data for the element.这里的想法是您为元素提供唯一的 ID,并将这些 ID 作为键用于存储元素数据的对象。

    This is nicely separated from the element (the browser owns the DOM, after all, not our code), but has the issue that entries in the object remain even if an element is removed.这与元素很好地分离(浏览器拥有 DOM,毕竟,不是我们的代码),但存在即使删除元素,对象中的条目仍然存在的问题。

    ES2015 addressed that issue by adding WeakMap , which is a map that can use any value (including a DOM object reference) as a key, and only holds the keys weakly (doesn't prevent them being removed from memory). ES2015 通过添加 WeakMap 解决了这个问题, WeakMap是一个可以使用任何值(包括 DOM 对象引用)作为键的映射,并且只保存键(不会阻止它们从内存中删除)。 If a key is removed, the entry is removed from the map.如果删除了某个键,则该条目将从映射中删除。 So in a browser with native WeakMap support (it cannot be correctly shimmed/polyfilled), once you have access to an element, you could do this:因此,在具有本机WeakMap支持的浏览器中(无法正确填充/填充),一旦您可以访问元素,您可以执行以下操作:

     // Initializing the map: const elementData = new WeakMap(); // Adding an entry to it: elementData.set(theElement, {my: "data"}); // Getting an entry form it: const data = elementData.get(theElement); if (data) { // It was there, use it... }
  2. Storing the data directly on the element, as an "expando" property.将数据直接存储在元素上,作为“expando”属性。 Once you have a reference to an element (from getElementById , querySelector , or any other way), you can create a property on it just by assigning:一旦您获得了对元素的引用(来自getElementByIdquerySelector或任何其他方式),您就可以通过分配在其上创建一个属性:

     theElement.__myExpandoProperty = {my: "data"};

    This is nicely tied to the element, doesn't require a separate data cache and the issues that come with it, gets cleaned up when the element is cleaned up, etc.这与元素很好地联系在一起,不需要单独的数据缓存和随之而来的问题,在元素被清理时被清理,等等。

    But has the problem that now we're storing our own properties on DOM elements.但是有一个问题,现在我们将自己的属性存储在 DOM 元素上。 This raises the possibility of colliding with properties the DOM itself uses, or other scripts use, so it's important to use a name that is extremely unlikely to conflict with something else.这增加了与 DOM 本身使用的属性或其他脚本使用的属性发生冲突的可能性,因此使用一个极不可能与其他内容冲突的名称非常重要。

    Separately, in now-obsolete versions of IE, expandos with objects on them (such as the above) had the potential for preventing garbage collection.另外,在现在已经过时的 IE 版本中,带有对象的 expandos(例如上面的)具有防止垃圾收集的潜力。

  3. For string data, using data-* attributes on the elements as Keir points out .对于字符串数据,正如 Keir 指出的那样,在元素上使用data-*属性。 I didn't include this in my original list because I was thinking of complex data, but for simple things this is absolutely an option.我没有将它包含在我的原始列表中,因为我正在考虑复杂的数据,但对于简单的事情,这绝对是一个选择。

jQuery (v2 and earlier) does a combination of #1 and #2: It adds a string expando property to the element to give it an ID (a simple string to avoid issues on now-obsolete versions of IE), and uses a separate data cache. jQuery(v2 及更早版本)结合了 #1 和 #2:它向元素添加了一个字符串 expando 属性以给它一个 ID(一个简单的字符串,以避免在现在过时的 IE 版本上出现问题),并使用一个单独的数据缓存。

First, the way you are getting the value attached with td is wrong.首先,您获取 td 附加值的方式是错误的。

It should be它应该是

target.getAttribute('value')

not不是

target.value

Another issue I think is player sequence,我认为的另一个问题是玩家顺序,

You are checking你正在检查

if(round === 1){

but default value of round = 0, so its the Player 2 who is playing first.但是默认值round = 0,所以它是第一个玩的玩家2。 You should set default value of round to 1 or compare it to 0 at first.您应该首先将 round 的默认值设置为 1 或将其与 0 进行比较。

Just update the code https://jsfiddle.net/1c0dqk01/只需更新代码https://jsfiddle.net/1c0dqk01/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM