JS中的appendChild问题 [英] Issue with appendChild in JS

查看:82
本文介绍了JS中的appendChild问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的JS代码:

$(document).ready(function () {
    'use strict';
    //cards
    $(".card").each(function () {
        //capture the data-* sets
        var img = this.dataset.img,
            alt = this.dataset.alt,
            heading = this.dataset.heading,
            text = this.dataset.text,
            url = this.dataset.url,

            //set the template
            template = '<img src="' + img + '" alt="' + alt + '"> <h3>' + heading + '</h3> <p>' + text + '</p>';

        //append the template to the parent
        this.appendChild(template);

    });

});

我正在尝试执行以下操作:

I am trying to do the following:

使用数据(img,alt,url,标题,文本)创建一个div,然后为每个div注入一个模板.

Create a div with a data-(img,alt,url,heading,text) and then for each of those divs, I want to inject a template.

但是,当我到达代码的最后一行时,chrome dev工具给了我这个错误:无法在'Node'上执行'appendChild':参数1的类型不是'Node'."

However, when I get to the last line of the code, chrome dev tools gives me this error: "Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'."

我不明白这是怎么回事,"this"是当前的$(.card")被循环,我只是在模板变量后面添加一个子代,根据我的想法,这应该可以工作...

I do not understand what is going wrong, "this" is the current $(".card") being looped over and i am only appending a child of the template variable, by my thinking, this should work...

感谢您的阅读,希望您能有所帮助,因为我很沮丧.

thanks for reading and I hope you can help because I am stumped.

推荐答案

鉴于您已经在使用jQuery,为什么不直接使用:

Given that you're already using jQuery, why not just use:

$(this).append(template);

请记住,jQuery .each()循环中的this是对当前 DOM节点的引用.如果要将其视为jQuery对象,则需要将其包装($(this)).

Keep in mind that this within a jQuery .each() loop is a reference to the current DOM node. If you want to treat it like a jQuery object, you need to wrap it ($(this)).

解释实际的错误消息:

无法在节点"上执行"appendChild":参数1的类型不是节点"."

"Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'."

不是在抱怨this不是节点类型",而是在抱怨template不是. domNode.appendChild()方法仅接受实际的DOM节点,而jQuery的$().append()则更健壮(接受DOM节点,另一个jQuery集合,HTML字符串等).

It's not complaining that this isn't "of type 'Node", it's complaining that template isn't. The domNode.appendChild() method only accepts actual DOM nodes, whereas jQuery's $().append() is far more robust (accepting a DOM node, another jQuery collection, an HTML string, etc.).

这篇关于JS中的appendChild问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆