jQuery:使用动态生成的变量作为选择器将 JSON 输入附加为内容

jQuery: using dinamically generated variables as selector to append JSON input as content

我在一个网站上工作,该网站基本上是按类别分隔的项目列表。用户可以添加一个类别,输入名称为以下形式:

    <form onsubmit="append_div(); add_cat(); return false;"> 
        <input id="new_category"/>
        <input type="submit" value="Add" id="add_btn_category" />
    </form>

调用了两个函数,append_div(),它动态地创建一个新的子项,将在其中插入新类别,add_cat(),它从服务器获取 JSON 并且应该设置指定选择器中的新内容。

    function append_div(){
            var nodelist = document.getElementsByTagName("h3").length; 
            var node = document.createElement("h3");
            node.id = "new_space" + nodelist;
            var new_sp = "'#new_space" + nodelist + "'"; // to be used in selector
            node.className= "categories";
            document.getElementById("append").appendChild(node);
        }

    function add_cat() {
            var url = 'add_category.php?category=' + $('#new_category').val();
            $.getJSON(url, function(data) {
                $(new_sp).html(data[0].category);
            });
        }

$(new_sp).html(data[0].category); 外一切正常。这是生成的进入三个不同类别的代码:aabbcc.

    `<div id="append">
        <h3 id="new_space0" class="categories"></h3>
        <h3 id="new_space1" class="categories"></h3>
        <h3 id="new_space2" class="categories"></h3>
    </div>`

但应该是:

        `<div id="append">
            <h3 id="new_space0" class="categories">aa</h3>
            <h3 id="new_space1" class="categories">bb</h3>
            <h3 id="new_space2" class="categories">cc</h3>
        </div>`

$(new_sp).html(data[0].category);中使用变量new_sp作为选择器似乎不起作用,但在检查了类似问题的帖子并尝试了许多建议的解决方案后我无法解决它。有什么想法吗?

var new_sp = "'#new_space" + nodelist + "'"; // to be used in selector

应该是

var new_sp = "#" + node.id; // to be used in selector

和变量new_sp应该在函数append_div之外定义或者应该是global才能在函数add_cat

中访问

类似

   var new_sp = "";
   function append_div(){
            var nodelist = document.getElementsByTagName("h3").length; 
            var node = document.createElement("h3");
            node.id = "new_space" + nodelist;
            new_sp = "#" + node.id; // to be used in selector
            node.className= "categories";
            document.getElementById("append").appendChild(node);
        }

    function add_cat() {
            var url = 'add_category.php?category=' + $('#new_category').val();
            $.getJSON(url, function(data) {
                $(new_sp).html(data[0].category);
            });
        }