当我点击第一个div中的p标签时,它会控制所有剩余的divs gameIds,而不是仅记录我点击的那个。我不确定我在这里做错了什么,有人有什么建议吗?
getGames().done(function(results){
$.each(results, function (i, gameData){
$.each(gameData, function(key, game){
var gamesHome = game.home_team_division;
var gamesAway = game.away_team_division;
if(gamesHome == "NCAA Division I" || gamesAway == "NCAA Division I"){
// console.log(this);
var gameId = game.id;
var homeTeam = game.home_team;
var awayTeam = game.away_team;
var pointTotal = game.total_points_bet;
var gameTime = game.game_time_hour;
var gameDate = game.game_time_date;
var gameId = game.id;
var network = game.broadcast_network;
var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
var hueTwo = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
var self = $(this);
$('.wrapper').append('\
<div class="main-wrapper col-lg-6 col-md-6 col-sm-12">\
<div class="game-cards">\
<div class="chart-container">\
<canvas id="'+ homeTeam +'" width="500" height="500"></canvas>\
</div>\
<div class="right-info">\
<h4>' + awayTeam + '<br>' + " @ " + '<br>' + homeTeam +'</h4>\
<h5 id="time-channel">'+ gameDate +' @ ' + gameTime + '<br>' + ' On ' + network +'</h5>\
<div class="total-points-live">\
<h5>Total Points Bet</h5>\
<h5 id="point-total">'+ pointTotal +'</h5>\
<p>'+ awayTeam +'</p>\
<input class="bet-input" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmount" placeholder="Wager Amount">\
<p>'+ homeTeam +'</p>\
<input class="bet-input" data-team-type="'+ homeTeam +'" type="number" pattern="[0-9]*" name="betAmount" placeholder="Wager Amount">\
<p class="bet-button">Click To Place Bet</p>\
</div>\
</div>\
</div>\
');
$('p').click(function(){
var self1 = $(this);
console.log(gameId);
console.log(self1);
});
答案 0 :(得分:0)
首先,您需要将$('p').click
移出each
块。目前,您多次绑定点击事件。其次,你必须稍微修改你的event
处理程序,如下所示。
此外,您需要在gameId
标记中的某处保存p
,以便以后可以检索。
...
<p gameid="' + gameId + '">'+ awayTeam +'</p>\
<input class="bet-input" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmount" placeholder="Wager Amount">\
<p gameid="' + gameId + '">'+ homeTeam +'</p>\
...
...
$('.wrapper').on('click', 'p', function() {
var self = $(this);
var gameId = self.attr('gameid');
console.log(gameId);
});