简体   繁体   English

“ AppendChild”在函数内部不起作用吗?

[英]“AppendChild” does not work inside a function?

"use strict";

Object.prototype.$ = function( selector ) {
    var sel = selector;
    if ( typeof sel == "string" ) {
        var elem = document.querySelectorAll( sel );
        if ( elem.length == 1 ) return elem[0];
        else if ( elem.length > 1 ) return elem;
    } else
        throw new Error( "Can't find element!" );
}

Object.prototype.crElem = function( e ) {
    var name  = document.createElement( e.name );
    var place = $( e.place );
    if ( e.value == undefined ) {
        place.appendChild( name );
    } else if ( e.value ) {
        name.innerHTML = e.value;
        place.appendChild( name );
    }
}

crElem({
    name: "button",
    place: ".slide"
});

in the console comes out this error: " Uncaught TypeError: place.appendChild is not a function " 在控制台中出现以下错误:“ Uncaught TypeError:place.appendChild不是函数”

Your $() function returns an array, and then you try to call .appendChild() on that. 您的$()函数返回一个数组,然后尝试在其上调用.appendChild() Of course that won't work. 当然那行不通。 You need to call it on a specific element, like place[0].appendChild(name) . 您需要在特定元素上调用它,例如place[0].appendChild(name) Also, what will you do when $() returns several elements? 另外,当$()返回几个元素时,您将怎么办?

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

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