如何在新创建的div文本中正确获取data属性值?
Hey, let's break down why you're seeing "undefined" in your new player div—this is a common context issue with this in jQuery.
The Root Problem
When you're building the new <div> element, you're using $(this).attr("data-player-balance") to pull the balance value. But right there, this doesn't refer to the new div you're creating—it points to the #entry-btn that was clicked. Since that button doesn't have a data-player-balance attribute, you get undefined as a result.
Easy Fixes
Here are a few straightforward ways to fix this:
Option 1: Use the hardcoded value directly
Since you're explicitly setting data-player-balance to 10 when creating the div, you can just use that number directly in the text:
$("<div/>", { "class": "player-label", "data-player-balance": 10, text: "Player " + playerCount + " balance: " + 10 }).appendTo("#player-label-lst");
Option 2: Create the element first, then reference its data
If you plan to use dynamic values later, create the div object first so you can access its own attributes:
// Create the div object first var newPlayerDiv = $("<div/>", { "class": "player-label", "data-player-balance": 10 // Swap this with a variable later if needed }); // Set text using the div's own data attribute newPlayerDiv.text("Player " + playerCount + " balance: " + newPlayerDiv.attr("data-player-balance")); // Append to the list newPlayerDiv.appendTo("#player-label-lst");
Option 3: Store the balance in a variable (cleanest for future changes)
If this player balance might come from a dynamic source later, storing it in a variable makes your code easier to maintain:
var playerBalance = 10; // Could be a dynamic value like user input later $("<div/>", { "class": "player-label", "data-player-balance": playerBalance, text: "Player " + playerCount + " balance: " + playerBalance }).appendTo("#player-label-lst");
Full Modified Code Example
Here's the complete working code using the variable approach:
$(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); // Use a variable for player balance var playerBalance = 10; $("<div/>", { "class": "player-label", "data-player-balance": playerBalance, text: "Player " + playerCount + " balance: " + playerBalance }).appendTo("#player-label-lst"); } $("#entry-btn").on("click", handleEntryButtonClick); });
内容的提问来源于stack exchange,提问作者Rodrigo Veiga

