调用具有特定索引值 NodeList 的函数

call a function with a specific index value of nodelist

本文关键字:NodeList 函数 索引值 调用      更新时间:2023-09-26

是否可以在存储div的nodelist的特定索引值上调用函数,如下所示:

var txtElem = txtdiv.getElementsByTagName("div");

我想要的是我在 txtElem 节点列表中存储分区列表,现在我想调用存储在节点列表中的第三个div 的单击事件上的函数。分区是动态创建的,它们没有任何 id,因此无法通过 id 访问它们。

从您的询问来看,这似乎可以:

function toPseudoArray(nodeList) {
    var ar = [];
    for(var i in nodeList)
        if(nodeList[i].nextSibling) // or for that case any other way to find if this is an element
            ar.push(nodeList[i]);
    return ar;
}

将 nodeList 传递给此函数,使用它返回的内容作为包含元素的数组,并且仅包含元素。

顺便说一下,你可以直接调用特定元素上的函数,只需使用 my_fab_function(txtElem[0]); -- 当然,直到你不超过计数。

这个问题还不清楚。看到jQuery标签,我想到了这些:

一种使用 .eq() 在指定索引上调用 jQuery 函数的方法:

var n = 1; //the index you need
$(txtElem).eq(n).css('color', 'red');

获取 DOM 元素的简单 Javascript:

var n = 1; //the index you need
var elem = txtElem[n]; //elem will hold the DOM element
//call simple DOM methods on it:
var s = elem.innerHTML;
//you can also call jQuery functions on it:
$(elem).css('color', 'red');

顺便说一下txtElem不是一个对象,它是一个NodeList,一个"类似数组的对象"。