繁体   English   中英

jquery .add()没有添加html元素

[英]jquery .add() not adding html element

我有一个元素数组,我希望将它放入一个jquery对象中。 jquery.add()似乎没有在我的jquery对象中添加元素。 我有控制台日志显示我添加的内容确实是html元素,但它们仍然没有添加到我做错了什么?

我的代码:

console.log('iterating')
console.log(content)
//add the content into the jquery item, and then we can load it into the qtip
_.each(additionalContent, function(value, element, list){
console.log('adding')
console.log(value)
console.log(content.length)
content.add(value) //trying content.add($(value)) gives the same result/output
console.log(content.length)
})

console.log('asdf')
console.log(content.length)
console.log(content)

======================打印以下内容:

iterating 
[p.nonVendor unselectable, selector: "", context: undefined, jquery: "1.9.1", constructor: function, init: function…]
adding 
<button class type=​"button" data-loading-text=​"OK" style=​"text-align:​ center;​ font-style:​ normal;​ font-variant:​ normal;​ font-weight:​ normal;​ font-size:​ 13px;​ line-height:​ normal;​ font-family:​ arial;​ color:​ rgb(255, 255, 255)​;​ background-color:​ rgb(0, 0, 255)​;​ z-index:​ 2;​ display:​ inline;​ left:​ auto;​ top:​ auto;​ width:​ 35.77777862548828px;​ height:​ 17.777777671813965px;​">​OK​</button>​
1 
1 
adding
<button class type=​"button" data-loading-text=​"Cancel" style=​"text-align:​ center;​ font-style:​ normal;​ font-variant:​ normal;​ font-weight:​ normal;​ font-size:​ 13px;​ line-height:​ normal;​ font-family:​ arial;​ color:​ rgb(255, 255, 255)​;​ background-color:​ rgb(0, 0, 255)​;​ z-index:​ 2;​ display:​ inline;​ left:​ auto;​ top:​ auto;​ width:​ 35.77777862548828px;​ height:​ 17.777777671813965px;​">​Cancel​</button>​
1 
1 
asdf 
1 
[p.nonVendor unselectable, selector: "", context: undefined, jquery: "1.9.1", constructor: function, init: function…]

.add()不会更改原始var,因此您需要将结果分配回“content”,如下所示:

content = content.add($(value));

要创建包含contentadditionalContent的对象的javascript数组,以下代码将起作用:

elements = [];
content.each(function(index, value) {
    elements.push(value);
});
additionalContent.each(function(index, value) {
    elements.push(value);
});

几点:

  • 你的每个函数的第一个参数将加载一个索引(类似于使用for循环:for(int index = 0; index <content.length; index ++),第二个参数是元素
  • jQuery方法.add用于处理选择器而不是对象集合,并且不会以代码所需的方式运行

然后可以在对象中使用elements集合 - 这是您需要的吗?

编辑 - 连接Jquery选择器:

作为wdosanjos指出,下面的工作-没有.each需要:

content = content.add(additionalContent);

要将css类香肠添加到两个选择器中的所有元素:

content.add(additionalContent).addClass('sausage');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM