使用jquery为动态生成的输入元素将值设置为数据属性[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

创建了一个新的input元素,并尝试使用jquery中的data方法添加data属性,但是无法追加该值

Js Fiddle to the above issue

var txtBox = $('<input/>', {
  "class": "myCustomClass",
  "type": "text"
});
$('#wrapper').append(txtBox);
txtBox.data('index', '1');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='wrapper'>Input Text Box : </div>
jquery custom-data-attribute
2个回答
0
投票
 var txtBox = $('<input/>', {
                "class" : "myCustomClass",
                "type" :"text",
                "data-index":""
            });
$('#wrapper').append(txtBox);           
txtBox.attr('data-index','ddddddddd');

0
投票

该守则工作正常我认为您正在寻找的代码是txtBox.attr('data-index', '1');

有关.data为什么不能按预期工作的更多信息,请查看此答案here

© www.soinside.com 2019 - 2024. All rights reserved.