【问题标题】:How to print a javascript variable in a html element?如何在 html 元素中打印 javascript 变量?
【发布时间】:2015-03-23 19:43:00
【问题描述】:

以下代码动态创建一个 span 元素。这部分有效。

我无法使用递增的 javascript 计数器变量更改每个新元素的名称。

<script>

var count = 0;

$(document).ready(function(){
    $("#addTag").click(function() {
        count++;
        $("#tags").append("<span id='tag'> <input type='text' name='tag[" + count + "]' /> </span>");
    });
});

</script>

期望的结果是:

<span id='tag'> <input type='text' name='tag[0]'/> </span>   
<span id='tag'> <input type='text' name='tag[1]'/> </span>    
<span id='tag'> <input type='text' name='tag[2]'/> </span>   

etc.. 取决于我选择创建的元素数量。

【问题讨论】:

  • 实际结果如何?
  • 如前所述,有多个元素具有与 'tag' 相同的 'id' 属性。这是一种不好的做法。
  • 请阅读HTML 属性,您不能拥有相同的id 属性。
  • 它工作正常,所需的o/p是什么
  • 看看这个小提琴:jsfiddle.net/on2h2Ltc 一切似乎都很好

标签: javascript jquery html


【解决方案1】:
/*
This is a self executing function, it'll execute automatically 
when the js file is loaded.
*/    var Tags = (function() {
        var container = null, count = 0;

        return {
            init: function() {
                container = $("#tags");
            },
            addTag: function() {
                count += 1;
                // like many others mentioned, I've changed the id="tag"
                // to class="tag", because id should be a unique 
                // value on a given page
                container.append('<span class="tag"><input type="text" name="tag['+count+']"</span>');
            }
        };

    })();

    $(document).ready(function() {
        // Once document has loaded, call the init() function
        // so that the variable container will be assigned $("#tags").
        Tags.init();

        $("#addTag").click(function()   {
            Tags.addTag();
        });
    });

这是一种更简洁的方法,不会用我们的任意变量污染globalscope 或本例中的jquery's document ready 范围。

P.S:您的代码运行良好,我只是向您展示了一种更简洁的方法,以及正确的做法(id 部分)。

【讨论】:

  • OP 没有添加元素的问题,没有人知道 OP 的问题到底是什么
  • @Legendary 是的,他可能在尝试与这些附加项目交互时遇到问题。 $("#tag") 只会将第一个元素返回给他。
【解决方案2】:

您可以使用闭包来保持计数变量。单击时,每次调用该函数时都会递增。

// Define our function called on click
var addEl = (function() {

  // These variables will be available in the function we return
  var count = 0;
  var myParent = $('#els');

  // Return our function.
  // This is a closure, our scope is maintained.
  return function() {
    myParent.append('<div name="tag[' + count + ']">' + count + '</div>');
    count++;
  };

})();

// Call our function on click.
// We can see that the counter will be incremented.
$('#addEl').on('click', addEl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addEl" type="button">Add</button>
<div id="els"></div>

【讨论】:

    【解决方案3】:

    $("#tags").append("&lt;span id='tag"+ count +"'&gt; &lt;input type='text' name='tag" + count + "' /&gt; &lt;/span&gt;");

    【讨论】:

    • 请您解释一下好吗?
    • 此输出与问题中提到的“期望结果”不匹配。
    • 添加解释将始终提高您的回答质量。
    猜你喜欢
    • 2011-02-07
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多