简体   繁体   中英

Array function not working on a JavaScript array created from element text

So I have the following element, that when clicked on calls the a JavaScript function response(tag). I pass the element "rops" itself to the function.

<li><div class="rops"><span class="rops-text"> tag2 </span></div></li>
<li><div class="rops"><span class="rops-text"> tag2 </span></div></li>

So when I click on one of these elements it adds them to an array. But now array functions work for that array, and they do for a normally created array. See the following working case and not working case:

They work if I create an array my self:

Working case:

var checkA = [];
checkA[0] = "tag1";
checkA[1] = "tag2";

alert(checkA.indexOf("tag2")); //Gives me correct answer. 

Not-working: Array created like this:

response(tag) {

 myArray[i] = String($(tag).text()); //at current point has ["tag1", "tag2"]

 //But if i do the same
 alert(myArray.indexOf("tag2")); //Gives me -1 (similar for other array function).

So in short, creating an array using element text cause the array functions not to work. Can anyone please help with this. I am not sure why this is happening? Thanks.

try this:

function result(tag){
   myArray = document.getElementsByTagName('span');
   alert(myArray.item('tag').innerHTML);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM