简体   繁体   English

在JavaScript中,如何使用jQuery更新属性

[英]In JavaScript, how to update attributes with jQuery

$(document).ready(function() {

    var hero_image = new Array();
    hero_image[0] = new Image();
    hero_image[0].src = 'assets/images/link.png';
    hero_image[0].id = 'image';

    hero_image[1] = new Image();
    hero_image[1].src = 'assets/images/bongo.png';
    hero_image[1].id = 'image';

    hero_image[2] = new Image();
    hero_image[2].src = 'assets/images/gandondorf.jpg';
    hero_image[2].id = 'image';

    hero_image[3] = new Image();
    hero_image[3].src = 'assets/images/queen.png';
    hero_image[3].id = 'image';

  var young_hero = ["Link", "Bongo Bongo", "Gandondorf", "Queen Gohma"];
  var health = [100, 70, 120, 50];
  var attack_power = [];
  var counter_power = [];

console.log(hero_image[0]);

function it_is_over_9000(){

  for (var i = 0; i < young_hero.length; i++) {

    var x = Math.floor(Math.random(attack_power)*20) + 3;
    var y = Math.floor(Math.random(attack_power)*10) + 3;

    attack_power.push(x);
    counter_power.push(y);

  }

}

function ready_board(){

  it_is_over_9000();

  for (var i = 0; i < young_hero.length; i++) {
    var hero_btns = $("<button>");
    hero_btns.addClass("hero hero_button");
    hero_btns.attr({
      "data-name": young_hero[i],
      "data-health": health[i],
      "data-image": hero_image[i],
      "data-attack": attack_power[i],
      "data-counter": counter_power[i],
      "data-index": i
    });


    hero_btns.text(young_hero[i]);
    hero_btns.append(hero_image[i]);
    hero_btns.append(health[i]);

    $("#buttons").append(hero_btns);

  }

}

function char(){

 $(".hero_button").on("click", function() {
    var hero = $(this);
    var hero_select = hero.data('index');


    for (var i = 0; i < young_hero.length; i++) {

      //var attack = ;

      if (i != hero_select){

        var enemies = $("<button>");
        enemies.addClass("hero enemy");

        enemies.attr({
          "data-power" : it_is_over_9000(),
          "data-name": young_hero[i],
          "data-health": health[i],
          "data-image": hero_image[i],
          "data-attack": attack_power[i],
          "data-counter": counter_power[i],
          "data-index": i
        });

        enemies.text(young_hero[i]);
        enemies.append(hero_image[i]);
        enemies.append(health[i]);

        $("#battle").append(enemies);

      }

    }

    $("#buttons").html($(this).data('name','health','image'));

    defender();

  });
}

function defender(){

  $(".enemy").on("click", function() {

    var enemy = $(this);
    var enemy_select = enemy.data("index");
    console.log(enemy_select);
    for (var i = 0; i < young_hero.length; i++) {

      if (i == enemy_select) {

        var defender = $("<button>");
        defender.addClass("hero defender");

        defender.attr({
          "data-name": young_hero[i],
          "data-health": health[i],
          "data-image": hero_image[i],
          "data-attack": attack_power[i],
          "data-counter": counter_power[i],
          "data-index": i
        });

        defender.text(young_hero[i]);
        defender.append(hero_image[i]);
        defender.append(health[i]);

        $("#defend").append(defender);

        $(this).remove();

      }

    }
  });

}

  $(".defend_button").on("click" , function(){

      if($(".defender").data("health") == 0){

        $(".defender").remove();

      } 

        $(".defender").attr({
          "data-health":  $(".defender").data("health") - $(".hero_button").data("attack")
        });       
  });

ready_board();
char();

});

I am trying to make a RPG game and I have the characters being generated the way I want them too but on the $(".defend_button").on("click" , function() at the end it doesn't update the data-health as it should. It only updates once but upon many clicks on the defend-button it doesn't update past the first time. 我正在尝试制作一个RPG游戏,我也按照我想要的方式生成角色,但是在$(“。defend_button”)上。(“点击”,函数()最后它不会更新数据健康应该是。它只更新一次,但是在多次点击保护按钮时它不会在第一次更新。

    <!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>

      <meta charset="UTF-8">
    <title>Zelda</title>

    <script type='text/javascript' src='https://code.jquery.com/jquery-2.2.0.min.js'></script>

    <script type = "text/javascript" src = "assets/javascript/game.js"></script>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="assets/css/style.css">

</head>

<style type="text/css">
    .hero { width: 125px; height:150px; border-style: solid; padding: 2px; float: left; margin: 2px; float: left; }

  .letter-button-color { color: darkcyan; }

  .fridge-color { color: orange; }

  #display { margin-top:78px; height:500px; width:220px; margin-left:60px; }

  #buttons { padding-top:60px; }

  #clear { margin-left: 20px; font-size: 25px; color: black; border-style: solid; width: 100px; }

    #image{width: 100px; height: 100px; margin-left: 10px;  }

</style>

<body>

<div class="row">

<div class="col-md-8">Select Your Character</div>

</div>

<div class="row">

<div id="buttons" class="col-md-8"></div>



</div>

<div class="row">

<div id="battle" class="col-md-8">


</div>

</div>

<div class="row">
    <div class="col-md-8">
        <button class="btn btn-primary defend_button">Defend</button>
    </div>
</div>

<div class="row">

<div id="defend">


</div>

</div>





</body>
</html>

You have to use .data() to update the health value. 您必须使用.data()来更新运行状况值。

var battleResult = $(".defender").data("health") - $(".hero_button").data("attack");
console.log("battleResult should be: "+battleResult );

$(".defender").data({
    "health":  battleResult
});

I played a little with your game. 我玩了一下你的游戏。
I found how to update the health display below the image too... 我发现如何更新图像下面的健康显示...
Since only updating the data wasn't changing anything on the screen. 由于只更新数据并未改变屏幕上的任何内容。

So, I left the above code there, for you to see it is effectively working. 所以,我把上面的代码留在那里,让你看到它有效地工作了。
But since you have to re-create the button to update health on scrreen... It is kind of useless. 但是因为你必须重新创建按钮来更新scrreen上的健康状况......这有点无用。

I also fixed the death condition 我还修复了死亡状况
from if($(".defender").data("health") == 0){ from if($(".defender").data("health") == 0){
to if($(".defender").data("health") <= 0){ to if($(".defender").data("health") <= 0){

I have to stop here before changing to much things. 在改变很多事情之前我必须在这里停下来。
See it in CodePen CodePen查看

Check your loop in it_is_over_9000() , because I think it is running uselessly too often. it_is_over_9000()检查你的循环,因为我认为它经常无用地运行。
And a dead defender has to be "buried" (lol). 一个死去的防守者必须“埋葬”(笑)。
Because when it is killed, a click on the defend button is kind of ressurrecting it. 因为当它被杀死时,点击防守按钮就可以重新获得它。 ;) ;)

Try setting the attribute like this. 尝试像这样设置属性。 Also, I recommend putting $(".defender") in a variable so you aren't requerying it each time. 另外,我建议将$(".defender")放在一个变量中,这样你每次都不会重新查询它。

var defender = $(".defender");

var loweredHealth = defender.data("health") -  $(".hero_button").data("attack");
defender.attr('data-health`, loweredHealth);

Update : 更新

It looks like the $('.defender') call will return multiple items. 看起来$('.defender')调用将返回多个项目。 You either need to select a specific defender or iterate through them individually like so: 您需要选择一个特定的defender或单独迭代它们,如下所示:

$('.defender').each(function(i, nextDefender) {
    var loweredHealth = nextDefender.data("health") -  $(".hero_button").data("attack");
    nextDefender.attr('data-health`, loweredHealth);
});`

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

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