如何在数组中存储唯一的函数名称

时间:2015-12-13 03:33:01

标签: javascript jquery html css jquery-mobile

我正在处理我的代码,想要弄明白我如何将可拖动对象存储到数组中,因为我正在创建一个数学游戏,它将识别可拖动元素并确定问题是否正确,这是我的代码

<script>
        $(function() {
            $( "#draggable1" ).draggable();
        });
  </script>
 <script>
        $(function() {
            $( "#draggable2" ).draggable();
        });
  </script>
 <script>
        $(function() {
            $( "#draggable3" ).draggable();
        });
  </script>
 <script>
        $(function() {
            $( "#draggable4" ).draggable();
        });
  </script>
 <script>
        $(function() {
            $( "#draggable5" ).draggable();
        });
  </script>
 <script>
        $(function() {
            $( "#draggable6" ).draggable();
        });
  </script>
 <script>
        $(function() {
            $( "#draggable7" ).draggable();
        });
  </script>
 <script>
        $(function() {
            $( "#draggable8" ).draggable();
        });
  </script>

然后我试图将这些可拖动元素放入数组

<div data-role="main" class="ui-content">
<script>
var theimagestwo = new Array();
theimagestwo[1] = "#draggable1";
theimagestwo[2] = "#draggable2";
document.getElementById("pagethree").innerHTML = theimagestwo[1];
</script>
我在做错了什么?它们只是作为文本出现

3 个答案:

答案 0 :(得分:1)

您可以为此创建一个函数并使用.each()

循环
$('[id^="draggable"]').each(function(){ // [id^="draggable"] mean select all elements there ids starts with draggable
    makeItDraggaple($(this));
});


function makeItDraggaple(el){
    el.draggable();
    $("#pagethree").append(el);
}

Working Demo

或者您只需使用 .each()而无需功能

$('[id^="draggable"]').each(function(){ // [id^="draggable"] mean select all elements there ids starts with draggable
     $(this).draggable();
     $("#pagethree").append($(this));
 });

Demo

答案 1 :(得分:1)

看一下代码的这一部分(我添加了评论):

// Create a new array
var theimagestwo = new Array();

// Push the strings "#draggable1" and "#draggable2" into the array
theimagestwo[1] = "#draggable1";
theimagestwo[2] = "#draggable2";

// Set inner HTML as theimagestwo[1] (which is "#draggable1")
document.getElementById("pagethree").innerHTML = theimagestwo[1];

所以,正如你所说的,结果是&#34;即将出现的文字&#34;因为它是文字。

如果我理解正确,您希望#pagethree的内容为元素 #draggable1(而不是字符串 "#draggable1")。所以你应该用以下代码替换上面的代码:

var theimagestwo = new Array();
theimagestwo[1] = $("#draggable1");
theimagestwo[2] = $("#draggable2");
$("#pagethree").empty().append(theimagestwo[1]);

答案 2 :(得分:0)

在@ Mohamed-Yousef的回答之上,如果您想将所有这些元素放在“pagethree”容器中,您可以通过添加一行来实现:

$('[id^="draggable"]').each(function(){
    makeItDraggaple($(this));
    $(this).appendTo("#pagethree");
});

执行$(this)两次效率低下,可能在某处没有缓存$("#pagethree")。但这是一个(未经测试的!)开始。