【问题标题】:jQuery: using dinamically generated variables as selector to append JSON input as contentjQuery:使用动态生成的变量作为选择器将 JSON 输入附加为内容
【发布时间】:2016-02-23 06:43:06
【问题描述】:

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

    <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 作为选择器似乎不起作用,但在检查了有类似问题的帖子并尝试了许多建议的解决方案后,我无法解决它。有什么想法吗?

【问题讨论】:

    标签: javascript jquery ajax jquery-selectors


    【解决方案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);
                });
            }
    

    【讨论】:

    • 谢谢,成功了!我之前已经尝试过以您的方式定义new_sp,但问题在于范围。
    猜你喜欢
    • 1970-01-01
    • 2013-02-13
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多