[英]jQuery .not() doesn't remove element?
I am grabbing a copy of some info from a page, but I do not want to include certain <option>
elements that appear inside <select>
elements on the page.我正在从页面中获取一些信息的副本,但我不想包含出现在页面上
<select>
元素内的某些<option>
元素。
Therefore, while I grab all the elements I want and am storing them in the variable fields
, I check to see if each element is a <select>
and if they have the specific <option>
that I don't want.因此,当我获取我想要的所有元素并将它们存储在变量
fields
,我会检查每个元素是否是<select>
以及它们是否具有我不想要的特定<option>
。
var field = allFields[i].innerHTML; //allFields is the raw HTML I'm iterating through
if ($(field).find("select").length > 0) { //If the element we're looking at contains a select
console.log("Found a select. It is in " + field);
console.log($(field).find(".bad-option");
field = $(field).not(".bad-option").prop("outerHTML"); //Use .not() to remove the elements which have the .bad-option class
// (and .prop("outerHTML") is just there to convert it back to a String instead of a jQuery object)
}
console.log("Adding " + field);
fields[i] = field; //Add the HTML, free of any unwanted options, to the `fields` variable
Based on jQuery's documentation , I would expect the .not()
function to remove any elements out of field
which have the bad-option
class.根据jQuery 的文档,我希望
.not()
函数可以从具有bad-option
类的field
删除任何元素。 Yet that is not the case at all.然而事实并非如此。 When I log
field
before and after using .not()
, it prints out the same thing.当我在使用
.not()
之前和之后记录field
,它会打印出相同的内容。 See the console output from the code above:查看上面代码的控制台输出:
Found a select. It is in <label>Description: <select><option>thing1</option><option class="bad-option">thing2</option></select></label>
-----------------
[jQuery list object size 1, containing an object called option.bad-option]
-----------------
Adding <label>Description: <select><option>thing1</option><option class="bad-option">thing2</option></select></label>
So what's going on?发生什么了? How do I remove an option with a certain class from from within a jQuery object?
如何从 jQuery 对象中删除具有某个类的选项? Why isn't
.not()
working?为什么
.not()
不起作用?
If I need to clarify anything, please let me know.如果我需要澄清任何事情,请告诉我。 I tried to make this question as specific as possible and would be happy to elaborate on any details further.
我试图使这个问题尽可能具体,并且很乐意进一步详细说明任何细节。
The documentation is perhaps a bit confusing: not
removes elements from the selection , not the DOM.文档可能有点混乱:
not
从selection 中删除元素,而不是 DOM。 If you want to remove the elements, then just filter and remove:如果要删除元素,则只需过滤并删除:
const processed = $(field);
processed.filter(".bad-option").remove();
field = processed.prop("outerHTML");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.