在新创建的div的文本中访问数据属性

时间:2018-05-16 02:02:13

标签: javascript jquery html

我在单击按钮时将新div添加到列表中,我希望我的新div的文本包含数据属性。

$(document).ready(function() {

    var balance = 0.00;
    var playerCount = 0;
    var avgBalance = 0.00;
    $("#server-balance").html("Server balance: $" + balance);
    $("#player-count").html("Players online: " + playerCount);
    $("#average-balance").html("Average player balance: $" + avgBalance);

    function handleEntryButtonClick() {

        playerCount++;
        balance = balance + 0.10;
        avgBalance = balance / playerCount;

        var balAdjust = balance.toFixed(2);
        var avgAdjust = avgBalance.toFixed(2);

        $("#server-balance").html("Server balance: $" + balAdjust);
        $("#player-count").html("Players online: " + playerCount);
        $("#average-balance").html("Average player balance: $" + avgAdjust);

        $("<div/>", {
            "class": "player-label",
            "data-player-balance": 10, 
            text: "Player " + playerCount + " balance: " + $(this).attr("data-player-balance")
        }).appendTo("#player-label-lst");

    }

    $("#entry-btn").on("click", handleEntryButtonClick);
});

我一直在生成一个新的div,文本为“Player X balance:undefined”。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

这是因为目前你创建了div,它还没有属性“data-player-balance”。您可以先尝试将其存储在变量中,然后在两个属性中使用它。

$(document).ready(function() {

    var balance = 0.00;
    var playerCount = 0;
    var avgBalance = 0.00;
    $("#server-balance").html("Server balance: $" + balance);
    $("#player-count").html("Players online: " + playerCount);
    $("#average-balance").html("Average player balance: $" + avgBalance);

    function handleEntryButtonClick() {

        playerCount++;
        balance = balance + 0.10;
        avgBalance = balance / playerCount;

        var balAdjust = balance.toFixed(2);
        var avgAdjust = avgBalance.toFixed(2);

        $("#server-balance").html("Server balance: $" + balAdjust);
        $("#player-count").html("Players online: " + playerCount);
        $("#average-balance").html("Average player balance: $" + avgAdjust);
        
        const playerBalance = 10;

        $("<div/>", {
            "class": "player-label",
            "data-player-balance": playerBalance, 
            text: "Player " + playerCount + " balance: " + playerBalance
        }).appendTo("#player-label-lst");

    }

    $("#entry-btn").on("click", handleEntryButtonClick);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="server-balance"></div>
<div id="player-count"></div>
<div id="average-balance"></div>

<div id="player-label-lst"></div>
<button id="entry-btn">Entry</button>