jquery - 为 p 标签分配属性 id 它不起作用

标签 jquery

我试图从数组中获取id名称,并尝试将id名称分配给每个p标签,当我单击按钮时,这些p标签会动态附加,html是:

<html>
<body>
    <div id="container">
        <button id="button">Add new div</button>
    </div>
</body>
</html>

脚本是:

$(document).ready(function () { 
    $('#button').click(function(){ 
        var data = [{'id':'user1'},{'id':'user2'},{'id':'user3'},{'id':'user4'},{'id':'user5'},];
        $.each(data, function(val) { 
            var light=$('<p></p>'); 
            light.attr('id',+val.id); 
            light.text('one'); 
            $("#container").append(light);
        }); 
    }); 
});

code is here

最佳答案

更改为:

$(document).ready(function () {
    $('#button').click(function() {
        var data = [{'id':'user1'},{'id':'user2'},{'id':'user3'},{'id':'user4'},{'id':'user5'},];
        $.each(data, function(i, val) { // added index parameter
            var light=$('<p></p>');
            light.attr('id', val.id);   // removed '+'
            light.text('one');

            $("#container").append(light);
        });
    });
});

另请参阅updated jsfiddle .

===更新===

var data = [{'id':'user1'},{'id':'user2'},{'id':'user3'},{'id':'user4'},{'id':'user5'},];
var position = 0;

$(document).ready(function () {
    $('#button').click(function() {
        var light=$('<p></p>')
            .attr('id', data[position].id)
            .text('one');
        $("#container").append(light);
        position++;
        position %= data.length;
    });
});

另请参阅我的updated jsfiddle .

关于jquery - 为 p 标签分配属性 id 它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8485778/

相关文章:

javascript - 进度条无法滚动

javascript - 当我在选项中有 2 个或更多单词时,Cufon + SelectBoxIt 组合广告三个点

php - 如何获取html页面源中未显示的内容

jquery - 在 AJAX JSON POST 请求中使用全局变量值

javascript - 是否可以使用 SignalR 更新 Google map 中的标记?

javascript - 在几分钟内得到两个日期之间的差异

javascript - X点击后模态滑入滑出

php - Codeigniter:this->datatables->select(sample)->from(sample)->where()

javascript - 从本地文件运行时 $.get() 无法正常工作

javascript - 选择输入字段时将父 DIV 滑动到顶部