如何在html元素中打印javascript变量

How to print a javascript variable in a html element?

本文关键字:打印 javascript 变量 元素 html      更新时间:2023-09-26

下面的代码动态创建一个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>   

等等。。这取决于我选择创建的元素数量。

/*
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范围。

第页。S: 您的代码运行得很好,我刚刚向您展示了一个更干净的方法和正确的方法(id部分)。

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

// 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>

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