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

时间:2015-11-20 17:15:35

标签: javascript jquery ajax jquery-selectors

我正在开发一个基本上是按类别分隔的项目列表的网站。用户可以将输入名称的类别添加到以下格式中:

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

1 个答案:

答案 0 :(得分:1)

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);
            });
        }