单击时调用变量函数

时间:2017-07-26 11:28:50

标签: javascript html css

我正试图在我正在构建的冒险游戏中触发项目效果,而我似乎无法弄清楚如何去做。基本上,当点击时,我想要运行其效果功能的任何项目。我很困惑。

    function showItems() {
      for (var i = 0; i < items.length; i++) {
        playerUi.innerHTML += '<div class="item-container"><a href="#" 
    class="item-name" onclick="items[i].effect">' + items[i].name + '</a><br 
    /><p class="desc-p">' + items[i].description + '<br />Value: ' + 
    items[i].price + '</p></div>';
      }
    }

    // Shows the inventory interface.
    $('#inv-btn').on('click', function() {
      playerUi.innerHTML = '<h3>Your Inventory:</h3>';
      showItems();
      playerUi.innerHTML += '<br /><br /><div class="gold-box">Gold: ' + 
    player.gold + '</div>';
    });

以下是我现在对我的项目的代码:

    // I  T  E  M  S
    function invItem(name, type, desc, price, eff) {
      this.name = name;
      this.type = type;
      this.description = desc;
      this.price = price;
      this.effect = eff;
    };

    var weakPotion = new invItem('Weak Potion', 'Consumable', 'A weak health 
    potion.', 10, healSelf(20));
    var brewersPotion = new invItem('Brewers Potion', 'Consumable', 'A 
    standard health potion.', 23, healSelf(45));

    function healSelf(amt) {
      if (player.currentHealth < player.maxHealth) {
        player.currentHealth += amt;
        if (player.currentHealth >= player.maxHealth) {
          player.currentHealth = player.maxHealth;
        }
      }
    }

要查看我目前在此click here上的内容。

以下是我的播放器对象。

    // Create our player object.
    var player = new Object();
    player.gold = 0;
    player.level = 1;
    player.strength = 5;
    player.intellect = 5;
    player.endurance = 5;
    player.agility = 5;
    player.currentExp = 0;
    player.reqExp = 100;
    player.skillPoints = 0;
    player.attPoints = 2;
    player.maxHealth = 0;
    player.currentHealth = 0;
    player.maxMana = 0;
    player.currentMana = 0;

2 个答案:

答案 0 :(得分:2)

让我们从头开始。这一行

var weakPotion 
     = new invItem('Weak Potion', 'Consumable', 'A weak health potion.', 10, healSelf(20));

已经没有按照你的想法做到了!它会立即执行该功能 - 这不是你想要做的。相反,您应该存储引用该函数以执行。通过返回一个稍后要调用的新函数来修复它

function healSelf(amt) {
  return function(){
    if (player.currentHealth < player.maxHealth) {
      player.currentHealth += amt;
      if (player.currentHealth >= player.maxHealth) {
        player.currentHealth = player.maxHealth;
      }
    }
  }
}

接下来,当您传递对函数的引用时,要稍后执行该函数,请使用括号:

onclick="items[i].effect()"

但是这仍然无法工作 - items[i]仅存在于循环中 - 而不是在页面运行时。解决此问题的一种方法是不直接附加onclick(尤其是在使用jQuery时),而是使用index()将点击处理程序附加到这些链接以找到正确的item

function showItems() {
  for (var i = 0; i < items.length; i++) {
    playerUi.innerHTML += '<div class="item-container"><a href="#" class="item-name">' + items[i].name + '</a><br /><p class="desc-p">' + items[i].description + '<br />Value: ' + items[i].price + '</p></div>';
  }
}

和其他地方

$(document).on('click','.item-name',function(){
   var index = $(this).index();
   items[index].effect();
});

答案 1 :(得分:1)

项目应该有唯一的ID,以便您可以轻松访问它们,从项目列表中删除等等。所以,最终得到类似的东西。

let playerUi = $('#inv');

let player = {
  currentHealth: 100,
  maxHealth: 100
};

let items = [];

function showItems() {
  for (var i = 0; i < items.length; i++) {

    let item = '<li data-itemid="' + items[i].id + '">' + items[i].name + '<br>Description: ' + items[i].description + '</li>';

    playerUi.append(item);

  }
}

function makeid() {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < 5; i++) // Change 5 to higher number for more unique IDs
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

function invItem(name, type, desc, price, eff) {
  this.id = makeid();
  this.name = name;
  this.type = type;
  this.description = desc;
  this.price = price;
  this.effect = eff;
};

function healSelf(amt) {
  return function() {
    console.log("Before heal:" + player.currentHealth);
    player.currentHealth = Math.min(player.currentHealth+amt, player.maxHealth);
    console.log("After heal:" + player.currentHealth);
  }
}

items[0] = new invItem('Weak Potion', 'Consumable', 'A weak health potion.', 10, healSelf(20));
items[1] = new invItem('Brewers Potion', 'Consumable', 'A standard health potion.', 23, healSelf(45));
items[2] = new invItem('Strongest Potion', 'Consumable', 'This potion is too strong.', 100, healSelf(80));

showItems();

$('li').on('click', function(e) {

  let id = e.target.dataset.itemid;
  let item = $.grep(items, function(e) {return e.id == id;})[0];
  console.log("Using: " + item.name);
  player.currentHealth -= 40;
  item.effect();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="inv">

</ul>