0

I am trying to make a page work for my website using the mootools framework. I have looked everywhere I can think of for answers as to why this isn't working, but have come up empty.

I want to populate several arrays with different data types from the html, and then, by calling elements from each array by index number, dynamically link and control those elements within functions. I was testing the simple snippet of code below in mootools jsfiddle utility. Trying to call an element from array "region" directly returns "undefined" and trying to return the index number of an element returns the null value of "-1".

I cannot get useful data out of this array. I can think of three possible reasons why, but cannot figure out how to identify what is really happening here: 1. Perhaps this array is not being populated with any data at all. 2. Perhaps it is being populated, but I am misunderstanding what sort of data is gotten by "document.getElementBytag()" and therefore, the data cannot be displayed with the "document.writeln()" statement. (Or am I forced to slavishly create all my arrays?) 3. Perhaps the problem is that an array created in this way is not indexed. (Or is there something I could do to index this array?)

html:
<div>Florida Virginia</div>
<div>California Nevada</div>
<div>Ohio Indiana</div>
<div>New York Massachussetts</div>
<div>Oregon Washington</div>

js:
var region = $$('div');
document.writeln(region[2]);
document.writeln(region.indexOf('Ohio Indiana'));

Thanks for helping a js newbie figure out what is going on in the guts of this array.

4

1 回答 1

2

$$将返回一个 DOM 元素列表。如果您只对那些 DOM 节点的文本感兴趣,那么请先将其提取出来。正如@Dimitar 在评论中指出的那样,调用get一个对象Elements可能会通过迭代集合中的每个元素并获取相关属性来返回一个数组。

var region = $$('div').get('text');

console.log(region[2]);                      // Ohio Indiana
console.log(region.indexOf('Ohio Indiana')); // 2

也使用,console.log而不是document.writelnor document.write,原因是调用此函数将清除整个文档并将其替换为传入的任何字符串。

看一个例子

于 2011-04-16T18:49:20.117 回答