为什么我的 JQuery 选择器返回 n.fn.init[0],它是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34494873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is my JQuery selector returning a n.fn.init[0], and what is it?
提问by jumps4fun
I have a set of dynamically generated checkboxes, where each of them has a data-id
attribute corresponding to a database integer id. When i populate my html-form with an object to edit, there is a list of integers representing which checkboxes should be checked. The checkboxes are wrapped in a div
with class checkbox-wrapper
.
我有一组动态生成的复选框,其中每个复选框都有一个data-id
对应于数据库整数 id的属性。当我用要编辑的对象填充我的 html 表单时,有一个整数列表,表示应选中哪些复选框。复选框被包裹在一个div
with 类中checkbox-wrapper
。
So html looks like this:
所以 html 看起来像这样:
<div class="checkbox-wrapper">
<input type="checkbox" id="checkbox1" data-id="1">
<label for="checkbox1">Checkbox 1</label>
</div>
<div class="checkbox-wrapper">
<input type="checkbox" id="checkbox2" data-id="2">
<label for="checkbox2">Checkbox 2</label>
</div>
<div class="checkbox-wrapper">
<input type="checkbox" id="checkbox3" data-id="99">
<label for="checkbox3">Checkbox 99</label>
</div>
Note that the id runs on auto increment index numbers, while data-id might have a different id value. I want to select them by data-id.
请注意,id 在自动递增索引号上运行,而 data-id 可能具有不同的 id 值。我想通过数据 ID 选择它们。
Now, using JQuery, I know I can select the relevant checkboxes like this:
现在,使用 JQuery,我知道我可以像这样选择相关的复选框:
$(".checkbox-wrapper>input[data-id='99']");
$(".checkbox-wrapper>input[data-id='1']");
This works in my console, in chrome, and it returns the relevant DOM-element. Likewise, this below, sets the checkboxes to checked:
这适用于我的控制台,在 chrome 中,它返回相关的 DOM 元素。同样,在下面,将复选框设置为选中:
$(".checkbox-wrapper>input[data-id='99']").prop("checked", "checked");
$(".checkbox-wrapper>input[data-id='1']").prop("checked", "checked");
However, if I iterate through a list of integers in my javascript code (not directly in the console), and log the returned elements, based on the id values, I get some weird results:
但是,如果我遍历我的 javascript 代码中的整数列表(不是直接在控制台中),并根据 id 值记录返回的元素,我会得到一些奇怪的结果:
var ids = [1,2]
$.each(ids, function(index, myID){
console.log($(".checkbox-wrapper>input[data-id='"+myID+"']"));
$(".checkbox-wrapper>input[data-id='"+myID+"']").prop("checked", "checked");
});
First of all, no checkboxes are checked. Second, my console prints strange results:
首先,没有选中复选框。其次,我的控制台打印出奇怪的结果:
n.fn.init[0]
context: document
length: 0
prevObject: n.fn.init[1]
selector: ".checkbox-wrapper>input[data-id='1']"
__proto__: n[0]
n.fn.init[0]
context: document
length: 0
prevObject: n.fn.init[1]
selector: ".checkbox-wrapper>input[data-id='2']"
__proto__: n[0]
The printed selector Strings seems perfect. The exact same selectors returns the DOM-elements, when written directly into the chrome console. Then they return objects like this:
打印的选择器字符串看起来很完美。当直接写入 chrome 控制台时,完全相同的选择器返回 DOM 元素。然后他们返回这样的对象:
[<input type=?"checkbox" id=?"checkbox1" data-id=?"1">?]
What is the n.fn.init[0], and why it is returned? Why are my two seemingly identical JQuery functions returning different things?
n.fn.init[0] 是什么,为什么会返回?为什么我的两个看似相同的 JQuery 函数返回不同的东西?
采纳答案by Hackerman
Another approach(Inside of $function
to asure that the each
is executed on document ready
):
另一种方法($function
确保在each
内执行document ready
):
var ids = [1,2];
$(function(){
$('.checkbox-wrapper>input[type="checkbox"]').each(function(i,item){
if(ids.indexOf($(item).data('id')) > -1){
$(item).prop("checked", "checked");
}
});
});
Working fiddle: https://jsfiddle.net/robertrozas/w5uda72v/
工作小提琴:https: //jsfiddle.net/robertrozas/w5uda72v/
What is the n.fn.init[0], and why it is returned? Why are my two seemingly identical JQuery functions returning different things?
Answer: It seems that your elements are not in the DOM yet, when you are trying to find them. As @Rory McCrossan pointed out, the
length:0
means that it doesn't find any element based on your search criteria.
n.fn.init[0] 是什么,为什么会返回?为什么我的两个看似相同的 JQuery 函数返回不同的东西?
答:当您尝试查找元素时,您的元素似乎尚未在 DOM 中。正如@Rory McCrossan 指出的那样,这
length:0
意味着它没有根据您的搜索条件找到任何元素。
About n.fn.init[0]
, lets look at the core of the Jquery Library:
关于n.fn.init[0]
,让我们看看 Jquery 库的核心:
var jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context );
};
Looks familiar, right?, now in a minified version of jquery, this should looks like:
Looks familiar, right?, now in a minified version of jquery, this should looks like:
var n = function( selector, context ) {
return new n.fn.init( selector, context );
};
So when you use a selector you are creating an instance of the jquery function; when found an element based on the selector criteria it returns the matched elements; when the criteria does not match anything it returns the prototype object of the function.
因此,当您使用选择器时,您正在创建 jquery 函数的一个实例;当根据选择器标准找到一个元素时,它返回匹配的元素;当条件不匹配任何内容时,它返回函数的原型对象。
回答by Arthur Tarasov
Here is how to do a quick check to see if n.fn.init[0]
is caused by your DOM-elements not loading in time. Delay your selector function by wrapping it in setTimeout
function like this:
以下是如何快速检查是否n.fn.init[0]
是由 DOM 元素未及时加载引起的。通过将其包装在setTimeout
如下函数中来延迟您的选择器函数:
function timeout(){
...your selector function that returns n.fn.init[0] goes here...
}
setTimeout(timeout, 5000)
This will cause your selector function to execute with a 5 second delay, which should be enough for pretty much anything to load.
这将导致您的选择器函数以 5 秒的延迟执行,这应该足以加载几乎所有内容。
This is just a coarse hack to check if DOM is ready for your selector function or not. This is not a (permanent) solution.
这只是一个粗略的技巧,用于检查 DOM 是否已准备好用于您的选择器功能。这不是(永久)解决方案。
The preferred ways to check if the DOM is loaded before executing your function are as follows:
在执行函数之前检查 DOM 是否已加载的首选方法如下:
1)Wrap your selector function in
1)将您的选择器功能包装在
$(document).ready(function(){ ... your selector function... };
2)If that doesn't work, use DOMContentLoaded
2)如果这不起作用,请使用DOMContentLoaded
3)Try window.onload, which waits for all the images to load first, so its least preferred
3)尝试window.onload,它等待所有图像首先加载,所以它最不受欢迎
window.onload = function () { ... your selector function... }
4)If you are waiting for a library to load that loads in several steps or has some sort of delay of its own, then you might need some complicated custom solution. This is what happened to me with "MathJax" library. This questiondiscusses how to check when MathJax library loaded its DOM elements, if it is of any help.
4)如果您正在等待一个库加载,该库分几个步骤加载或有自己的某种延迟,那么您可能需要一些复杂的自定义解决方案。这就是“MathJax”库发生在我身上的事情。这个问题讨论了如何检查 MathJax 库何时加载其 DOM 元素,如果有帮助的话。
5)Finally, you can stick with hard-coded setTimeout
function, making it maybe 1-3 seconds. This is actually the very least preferred method in my opinion.
5)最后,您可以坚持使用硬编码setTimeout
功能,使其可能为 1-3 秒。在我看来,这实际上是最不受欢迎的方法。
This list of fixes is probably far from perfect so everyone is welcome to edit it.
这个修复列表可能远非完美,所以欢迎大家编辑它。
回答by Basheer AL-MOMANI
I faced this issue because my selector was depend on id
meanwhile I did not set id for my element
我面对这个问题,因为我的选择是依赖于id
同时I did not set id for my element
my selector
was
我selector
是
$("#EmployeeName")
but my HTML element
但我的 HTML element
<input type="text" name="EmployeeName">
so just make sure that your selector criteria are valid
所以只需确保您的选择器标准有效
回答by celerno
Your result object is a jQuery element, not a javascript array. The array you wish must be under .get()
您的结果对象是一个 jQuery 元素,而不是一个 javascript 数组。您希望的数组必须在 .get() 下
As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array. http://api.jquery.com/map/
由于返回值是一个包含数组的 jQuery 对象,因此在结果上调用 .get() 以使用基本数组是很常见的。 http://api.jquery.com/map/
回答by Train
I just want to add something to these great answers. If your DOM
element ins't loading in time. You can still set the value.
我只想为这些很棒的答案添加一些东西。如果您的DOM
元素没有及时加载。您仍然可以设置该值。
let Ctrl = $('#mySelectElement');
...
Ctrl.attr('value', myValue);
let Ctrl = $('#mySelectElement');
...
Ctrl.attr('value', myValue);
after that mostDOM
elements that accept a value attribute should populate correctly.
之后,大多数DOM
接受 value 属性的元素应该正确填充。
回答by Subhan Raza
Error is that you are using 'ID' in lower case like 'checkbox1' but when you loop json object its return in upper case. So you need to replace checkbox1 to CHECKBOX1.
错误是您使用的是小写的“ID”,例如“checkbox1”,但是当您循环 json 对象时,它会以大写形式返回。所以你需要将 checkbox1 替换为 CHECKBOX1。
In my case :-
就我而言:-
var response = jQuery.parseJSON(response);
$.each(response, function(key, value) {
$.each(value, function(key, value){
$('#'+key).val(value);
});
});
Before
前
<input type="text" name="abc" id="abc" value="">
I am getting the same error but when i replace the id in html code its work fine.
我遇到了同样的错误,但是当我在 html 代码中替换 id 时,它工作正常。
After
后
<input type="text" name="abc" id="ABC" value="">