Jquery.data返回未定义的结果 [英] Jquery.data returning undefined results

查看:154
本文介绍了Jquery.data返回未定义的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的是从节点js server为每个节点动态创建li标签的项目列表,然后以某种方式嵌入每个创建的来自服务器的ID HTML元素作为自定义属性或ID。我希望这是有道理的。 
感谢先进的花时间提供帮助,我对此有点新意,所以任何帮助都将受到高度赞赏。
我做错了什么?还有另一种方法可以实现这一目标吗?
我包含了我在下面尝试过的代码。





我尝试了什么:



  //  首先获取列表来自服务器的项目 
items.forEach( function (item){
// 将列表添加到变量以便稍后追加到html页面
var newItem = ` < li > $ {item.name} < / li > `;
//我试过Jquery.data和.attr,两者都返回undefined
$(newItem)。 data('id',item._id);
//我也试过了vanilla javascript方法:.setAt致敬,我得到一个错误,它不是一个功能。
newItem.setAttribute('id',item._id);

console.log($(item).data('id')); //未定义结果

解决方案

{item.name} < / li > `;
//我试过Jquery.data和.attr,两者都返回undefined


(newItem).data('id',item._id);
//我也试过了vanilla javascript方法:.setAttribute我得到一个错误,它不是一个函数。
newItem.setAttribute('id',item._id);

console.log(


(item).data('id')); //未定义结果


I'm trying to do is get a list of items from a node js server create li tags dynamically for each one, then somehow embed the ID that is coming from the server in each created HTML element as a custom attribute or an ID. I hope this make sense.
Thanks in advanced for taking the time to help, I'm kinda new to this, so any help would be highly appreciated.
What am I doing wrong? and is there another way to accomplish this?
I included the code I tried below.



What I have tried:

//First getting thelist of items from the server
items.forEach(function(item) {
//adding the list to a variable to append later on to the html page
          var newItem= `<li>${item.name}</li>`;
            //I tried Jquery.data and .attr and both returns undefined
           $(newItem).data('id', item._id);
//I also tried the vanilla javascript method: .setAttribute and I get an error that it's not a function.
          newItem.setAttribute('id', item._id);

               console.log($(item).data('id'));//undefined result

解决方案

{item.name}</li>`; //I tried Jquery.data and .attr and both returns undefined


(newItem).data('id', item._id); //I also tried the vanilla javascript method: .setAttribute and I get an error that it's not a function. newItem.setAttribute('id', item._id); console.log(


(item).data('id'));//undefined result


这篇关于Jquery.data返回未定义的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆