我有一个名为array的数组(将其注释为TOP array),这个数组实际上包含不同div元素的类。我加入了数组,使表单的每个元素都是".1“或".4”等,现在如果单击其中的任何类,我将其html存储在变量hello中,然后从hello的html中提取类,并将它们放入数组中。现在我需要知道用户点击了什么,所以我创建了一个数组blaharray来比较hello和它的数组元素。通过这样做,我尝试将hello数组的"1“或"6”类与blaharray相匹配。如果匹配,我会加上".“使用匹配的hello元素,使其类似于".7“,表示用户单击的类,我将其存储在userclicked中。但是,如果单击".1“类,则userclicked不会返回任何内容。所以我试着检查".1“类的hello数组中是否有问题,发现在for循环之外(疯狂代码开始的地方),hello返回了类".1”的正确数组,即"1",“col xs-4”,“col md-4”,但在for循环内部,当我控制台hello时,当".1“被点击时,它在控制台中没有输出。但是如果我单击任何其他类,比如2到9,它会给出正确的hello和userclicked内部和外部输出,为什么当hello是"1",“loop.But -xs-4”,“col md-4”时(我是指当单击".1“时),它不工作?
array = [".1,.2,.3,.4,.5,.6,.7,.8,.9"]; //TOP array
$(array.join("")).click(function() {
$(this).html(input);
var hello=this; //it will store the html of clicked class
hello=hello.className.split(/\s+/); //it will extract the classes and put them in an array like this---> ["1", "col-xs-4", "col-md-4"]
var blaharray=["1","2","3","4","5","6","7","8","9"];
console.log(hello); //here it works giving ["1", "col-xs-4", "col-md-4"]
for(var i=0;i<hello.length;i++){ //Crazy code starts
if(blaharray.indexOf(hello[i])>0){ //it will check if any class in hello array is found in blah array,we are checking here for class "1" of ["1", "col-xs-4", "col-md-4"]
userclicked="."+hello[i]; //if it is found, it adds a "." to it to make ".1" of TOP array joined by ""(I will use it in some code)
console.log(hello); //here the console produces nothing i.e blank ONLY if ".1" is clicked
}
} //Crazy code ends to tell us what the user clicked
});这是供我参考的类的html,我有1,2等类用于div。
<div class="container-fluid">
<div class=" yo text-center row">
<h1>Tic Tac Toe by Uzma</h1>
<div class="col-xs-12 col-md-12 we">
<div class="row ">
<div class="1 col-xs-4 col-md-4"></div>
<div class="2 col-xs-4 col-md-4"></div>
<div class="3 col-xs-4 col-md-4"></div>
</div>
<div class="row">
<div class="4 col-xs-4 col-md-4"></div>
<div class="5 col-xs-4 col-md-4"></div>
<div class="6 col-xs-4 col-md-4"></div>
</div>
<div class="row">
<div class="7 col-xs-4 col-md-4"></div>
<div class="8 col-xs-4 col-md-4"></div>
<div class="9 col-xs-4 col-md-4"></div>
</div>
</div>
</div>
</div>下面是用于检查不同点击的Codepen http://codepen.io/meow414/pen/QExLOG?editors=1001
发布于 2016-07-26 21:14:43
这是因为blaharray中'1‘的索引是0,永远不会通过if条件:
var blaharray=["1","2","3","4","5","6","7","8","9"];
console.log(blaharray.indexOf("1"));
你应该这样做:if(blaharray.indexOf(hello[i])>=0){
IndexOf函数返回"The first index of the element in the array; -1 if not found.“
https://stackoverflow.com/questions/38590585
复制相似问题