检索" ID"从JQuery的阵列 [英] Retrieve "id" from array in JQuery

查看:126
本文介绍了检索" ID"从JQuery的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个小游戏,我有这样一个数组几个障碍:

I'm working on a small game and I have several obstacles in an array like so:

obstacles = [ { id: '#car' }, { id: '#house' }, { id: '#door' }, ];

在我的code的第二部分,我有:

In the second part of my code, I have:

JQuery的:

 $('#alert').hide();
 for (index in obstacles) {

        object = $(obstacles[index]["id"]);


    obj_left = object.position().left + parseInt(object.css("margin-left"));
    obj_top = object.position().top + parseInt(object.css("margin-top"));



      if ((((posX > (obj_left - me.width() / 2)) && 
      (posX < (obj_left + object.width() + me.width() / 2)))) && 
     (posY > (obj_top - me.height() / 2)) && 
     (posY < (obj_top + object.height() + me.height() / 2))) {


            // Cannot walk 
            return false;
        }
    $('#alert').show(); // display error message 
    }
    // Can walk again
    return true && $('#alert').hide();   // hide error again                 
}

HTML:

<div id="alert">//...</div>
<div id="character"></div>
<div class="door" id="door"></div>
<div class="house" id="house"></div>
<div class="car" id="car"></div>

我测试了它和它的工作太棒了。
但不是对于每个障碍显示一个警告,我只想取回的某些障碍的值(即:如果玩家击中一辆汽车,输出你打一个车!,或者如果玩家击中一所房子,输出您不能输入)。

I tested it out and it worked great. But instead of displaying an alert for every obstacle, I just want to retrieve the value of a certain obstacle (i.e: if the player hits a car, output "You hit a car!" or if the player hits a house, output "You may not enter").

希望我已经简单,提供了code相当数量。

Hope I've been straightforward and have provided a fair amount of code.

编辑:这里有一个链接,我也跟着教程:的 http://blog.oscarliang.net/pokemon-online-game-theme-tutorial/

Here's a link to the tutorial I followed: http://blog.oscarliang.net/pokemon-online-game-theme-tutorial/

谢谢!

推荐答案

如果我理解正确的话,这会做你想要什么:

If I understand you correctly, this will do what you want:

注意:你需要包括jQuery的为这当然是工作

note: you'll need to include jQuery for this to work of course

<script>
         obstacles = [ { id: 'car' }, { id: 'house' }, { id: 'door' }, ]
         $("div").on("click", function() {
             var found = false;
             var obj   = $(this).prop("id");
             for(i=0;i<obstacles.length;i++) {
                 if(obstacles[i].id == obj) {
                        found = true;                     
                 }
             }
             alert(found ? "You hit a " + obj + "!" : "You may not enter");
         });
</script>

<div id="car">Car</div>
<div id="house">house</div>
<div id="door">door</div>
<div id="bank">bank</div>

这篇关于检索&QUOT; ID&QUOT;从JQuery的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆