简体   繁体   English

元素是不确定的吗?

[英]elem is undefined?

When I run the following piece of code, the firebug console says that elem is undefined, although...it isn't! 当我运行以下代码时,firebug控制台会说elem是未定义的,尽管...不是!

var domTools = {};
domTools.searchInElements = function (elem, pattern) {
    if (pattern.constructor !== RegExp) {
        throw "Pattern must be a RegExp";
    }
    if (elem.constructor !== String) {
        throw "Element must be a String";
    }
    elem = document.getElementsByTagName[elem];
    var matches = [];
    for (e = 0; e < elem.length; e++) {
        if (pattern.test(elem[e].innerHTML)) {
            matches.push(elem[e]);
        }
    }
    return matches;
}
domTools.searchInElements("p", /hello/);

It gives me the error during the for statement. 它在for语句中给了我错误。 All this code is being run whle the page is already loaded. 页面已加载时,所有这些代码都在运行。 Why is this happening? 为什么会这样呢?

It's () and not [] ()而不是[]

elem = document.getElementsByTagName(elem);

Think of getElementsByTagnName() as a function call so you won't forget that it uses () . getElementsByTagnName()视为函数调用,这样您就不会忘记它使用() And don't forget using the developer console F12 to spot these problems. 并且不要忘记使用开发人员控制台F12来发现这些问题。

As Joseph the Dreamer already found the bug that was causing the error because you've used document.getElementsByTagName[elem] instead of document.getElementsByTagName(elem) . 正如约瑟夫那样,梦想家已经找到了引起该错误的错误,因为您使用的是document.getElementsByTagName[elem]而不是document.getElementsByTagName(elem)

But you may face another problem with this call domTools.searchInElements("p", /hello/); 但是您可能会在此调用domTools.searchInElements("p", /hello/);遇到另一个问题domTools.searchInElements("p", /hello/); because it'll match hello, helloo, hellos etc so you should use 因为它会匹配hello, helloo, hellos etc所以您应该使用

domTools.searchInElements("p", /^hello$/)

OR just another idea here . 还是这里的另一个想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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