简体   繁体   English

点击时更新DIV内容,而无需直接知道其ID

[英]Update DIV content on click without directly knowing its ID

I am building 2D tile game map. 我正在构建2D瓷砖游戏地图。 Each tile is a div in 2D array (var tiles = []). 每个图块都是2D数组中的一个div(可变图块= [])。 Below is the function which builds a tile based on some arguments defined somewhere else: 以下是根据其他地方定义的一些参数构建图块的函数:

function Tile(rnd, px, py, nid) {
var self = this;
var _types = ["grass","forest","hills","swamp","forest", "mountains"];

var height = 60;
var width = 60;
var tileID = nid // new numeric tile id

var id = "tile_"+px+py+rnd; // old tile ID
var x = px;
var y = py;

var type = _types[rnd];
var img = 'img/maptiles/'+type+'.png';

this.Draw = function() {
    var div = $("<div class='tile'></div>");
    div.attr('id',tileID).data('type',type).data('x',x).data('y',y);
    div.get(0).tile = self;
    div.css({top:height*y, left:width*x});
    div.css({"background":"url('"+img+"')"});
    div.appendTo('#map-content');
};


this.Alert = function() {
    alert("Tile type: "+type+". Tile ID: "+tileID+" ");
};

this.Move = function(){ // moves player to available tile, in this case if player stands to a tile before the clicked one
    alert("start move! Tile type: "+type+". Tile ID: "+tileID+" ");
    if (playerPosition === tileID - 1) {
        $("#player").remove();
        $("#????")").append('<img id="player" src="Pictures/maptiles/player.png" />');
        playerPosition = tileID;
        alert("Player position now: " + playerPosition);

    }


};

} }

As a result I end up with mxn map made of divs each with a unique numeric ID starting with 1. I know that using numeric IDs for elements is(was?) frowned upon, though HTML5 specs do not actually prohibit this anymore. 结果,我最终得到了由div组成的mxn映射,每个div都有一个以1开头的唯一数字ID。我知道使用元素的数字ID是(过去了?),尽管HTML5规范实际上不再禁止这样做了。

Now what I want to do is to place a player icon (player.png) depending on player's position. 现在我要做的是根据播放器的位置放置一个播放器图标(player.png)。 Starting position is 1 and I am using tiles (aka divs) numeric IDs to calculate legal moves (can move only to bordering tiles). 起始位置为1,我正在使用图块(又称div)数字ID来计算合法移动(只能移动到边界图块)。

When a tile is clicked this.Move is called. 单击磁贴时将调用this.Move。 Its purpose is to check if player can move on a clicked tile (just one IF statement for now to test) and must remove player.png and redraw it on the clicked div. 其目的是检查玩家是否可以在单击的图块上移动(现在仅测试一个IF语句),并且必须删除player.png并在单击的div上重绘它。

Here I run into a problem since I need to somehow use the tileID (which is equal to Div ID) to tell browser to append the DIV which is belong clicked (as I obviously do not write a function for every div on the field). 在这里我遇到了一个问题,因为我需要以某种方式使用tileID(等于Div ID)告诉浏览器附加属于单击的DIV(因为我显然不在字段上为每个div编写函数)。 I think that since I can get the DIV id on click I can use it somehow. 我认为,由于我可以点击获得DIV ID,因此可以使用它。

I tried to experiment with this.div.id:eq("+tileID+") but with no luck. 我尝试使用this.div.id:eq("+tileID+“)进行实验,但是没有运气。

UPD: UPD:

Adding click handler as requested. 根据要求添加点击处理程序。 Note this is within var Map, which is responsible for building the map, rendering and handling some user input: 请注意,这在var Map中,该地图负责构建地图,渲染和处理一些用户输入:

var Map = new function() {
var maxHorz = 20;
var maxVert = 5;

var tiles = [];
this.init = function() {
    for(var i=0; i<maxVert; i++) {
        tiles[i] = [];
        for(var j=0; j<maxHorz; j++) {
            tiles[i][j] = new Tile(Math.random()*6|0, j, i, tileID++);
        }
    }  

    Render();
    Setup();
};

this.GetMap = function() {
    return tiles;
};

var Render = function() {
    $.each(tiles, function(k,v){
        $.each(v, function(k,t){
            t.Draw(); 
        });
    });
};

var Setup = function(){
    $('#map-content').on('click','div.tile', function(e){
         //var tile = tiles[$(this).data('y')][$(this).data('x')];
         this.tile.Move();
    });
}

this.Redraw = function(x,y) {

};

} }

Map.init(); Map.init();

找到答案了,最后:)

$('#player').detach().appendTo($('#'+tileID))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 获取内容 <div> 知道它的身份 - Get content of <div> knowing its id 有没有办法在不知道其类名或ID的情况下选择父div? - Is there a way to select parent div without knowing its class name or ID ? Firebase:如何在不知道其唯一ID的情况下更新记录的值项? - Firebase: HowTo update the value item of a record without knowing its unique id? 从javascript中的字符串中删除带有id的Div,而不删除其内容 - Remove Div with a id from a string in javascript, without removing its content 将焦点设置为动态创建的输入字段,而无需知道其ID - Setting Focus on dynamically created input field without knowing its ID Angular &amp; Firebase 实时数据库。 如何让孩子知道其 id 属性但不知道其父节点 - Angular & Firebase Realtime-Database. How to get child knowing its id property but without knowing its parent node 刷新 <div id=“RefhreshableDiv”> 内容点击按钮 - Refresh <div id=“RefhreshableDiv”> content on button click 如何在不使用ID的情况下删除div - How to remove a div without using its ID 点击后将内容附加到div,而无需重新加载页面 - Append content to div on click without page reloading 在没有Jquery的情况下单击可循环浏览div内容 - Cycle through div content on click without Jquery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM