传递了Object函数中的参数,但执行为Null

时间:2014-10-12 19:27:01

标签: javascript object null arguments

我已经为个人JS库创建了一个对象,但由于某种原因,在我的一个页面上,其中一个函数参数很奇怪。

参数正在传递,因为它们在记录时返回值,但是一旦parID传递到getElementById方法,它就会返回null。

HTML:

<body id="body">
   <header>
   <h1>Title</h1>
</header>
   <article id="run"></article>
</body>

JavaScript的:

图书馆代码:

 var doc = {
    make: function (tagName, id, parID, txt){ // Creates & appends elements, sets ID, initializes and sets text in textNodes
        // var body = document.getElementsByTagName('body')[0];


        var cVar = document.createElement(tagName);
        if(id.length !== 0){
            cVar.setAttribute('id', id);
        }

        if(parID === undefined || parID === null ){
            document.body.appendChild(cVar);
        }
        else if(parID.length === 0){
            //
        }
        else{
            console.log(parID); // **HERE** This returns the passed argument
            var parIDSel = document.getElementById(parID); // Something happens here ??
            console.log(parIDSel); // **ALSO HERE** This returns "null"
            parIDSel.appendChild(cVar); // "Uncaught TypeError: Cannot read property 'appendChild' of null"
        }

        if(txt !== undefined){
            var getCVar = cVar;
            var textNode = document.createTextNode(txt);
            getCVar.appendChild(textNode);
        }
        // if(code !== undefined){
        //     var getCVar = cVar;
        //     getCVar.innerHTML = code;
        // }
        return doc;
    }, 
//etc...

调用属性的方法:

doc.make('p','content','run','hello world');

任何可观察到的问题?同样,这是这个问题出现的第一次也是唯一一次;我使用完全相同的脚本在另一个页面上工作,没有问题。

0 个答案:

没有答案