2017-12-18 93 views
0

jQuery和尝试添加数据属性使用jquery的数据的方法,但是不能够追加值设定值数据属性使用用于创建一个新的输入元件动态地生成的输入元件

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>

+1

您的代码工作正常:https://jsfiddle.net/bb69fgbj/3/。混淆的根源很可能是因为data()不更新DOM,所以'data-index'属性不会出现在检查器中。只要你使用'data()'的getter来检索这个值,你就没有问题了:'var index = txtBox.data('index')' –

+0

除了@ RoryMcCrossan的评论,如果你想要数据要在HTML上显示,可以使用['attr'](http://api.jquery.com/attr/)方法。 – 31piy

+0

使用.attr()来解决问题。谢谢:) –

回答

0
var txtBox = $('<input/>', { 
       "class" : "myCustomClass", 
       "type" :"text", 
       "data-index":"" 
      }); 
$('#wrapper').append(txtBox);   
txtBox.attr('data-index','ddddddddd'); 
+0

@Rory McCrossan是对的。但是,如果我们想确认attr也是不错的选择,那么数据就是html5的功能。 –

0

的代码工作fineI认为你正在寻找的代码是 txtBox.attr('data-index', '1');

更多的信息,为什么你所期望的。数据没有工作,检查这个答案 here

+0

最好将链接的详细信息添加到您的帖子中,以防万一它死了。 –