有没有办法让阵列中的主题可点击?

时间:2014-01-03 10:05:52

标签: javascript arrays

我想用javascript制作游戏。游戏的一部分是有一个“商店”,用户可以点击商店里的东西,它会影响得分。

var i;
var shop = new Array();
shop[0] = "Bins:" + "  " + "5";
shop[1] = "Shops:" + "  " + "60";
shop[2] = "Factories: " + "   " + "190";
shop[3] = "Warehouses:" + "   " + "600";
shop[4] = "Over sies:" + "   " + "1,500";

for (i=0; i<shop.length; i++){
  document.write(shop[i] + "<br>")
}

这就是阵列的样子,那么用户可以点击“商店”中的对象并使其影响游戏的整体得分吗?

1 个答案:

答案 0 :(得分:0)

这看起来像是简单的js / html。为了让你滚动,这是你可以尝试的。

// First, define the array in a bit more data-friendly way.
var i, itemEl, valueEl, liEl, qty, totalScore, shop = [];
shop.push({item: 'Bins', quantity: 5});
shop.push({item: 'Shops', quantity: 60});
shop.push({item: 'Factories', quantity: 60190);
shop.push({item: 'Warehouses', quantity: 600});
shop.push({item: 'Over sies', quantity: 1500});

// then, create a javascript handler for clicks. It will increase the total score
totalScore = 0;
function addToScore(val) {
    totalScore += val;
    alert('New score: ' + totalScore);
}

// finally, output this as HTML. Find an UL element and add each item row.
var itemsContainer = document.getElementById('items');

for (i = 0; i < shop.length; i++) {
    // for each shop item, create a text node holding the label
    // and a clickable span containing the number. When the user clicks on the number
    // the totalScore increasing method will be called.
    // you can add other html elements like this, like
    // decreasing score, removing the item, whatever
    itemEl = document.createTextNode(shop[i].item + ': ');
    valueEl = document.createElement('span');
    valueEl.setAttribute('onclick', 'addToScore(' + shop[i].quantity + ')');
    liEl = document.createElement('li');
    liEl.appendChild(itemEl);
    liEl.appendChild(valueEl);
    itemsContainer.appendChild(liEl);
}

您的HTML应该只包含itemsContainer,例如&lt; ul&gt;元件。

<ul id='items'></ul>

这只是一个例子。有一些事情没有“正确”完成,但代码将起作用。当你从这开始,你将学习其他东西,然后回来询问如何改进你的代码。