所以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>
请注意,id在自动增量索引号上运行,而data-id可能具有不同的id值.我想通过data-id选择它们.
现在,使用JQuery,我知道我可以选择相关的复选框,如下所示:
$(".checkBox-wrapper>input[data-id='99']"); $(".checkBox-wrapper>input[data-id='1']");
这适用于我的控制台,在chrome中,它返回相关的DOM元素.同样,在下面,将复选框设置为选中:
$(".checkBox-wrapper>input[data-id='99']").prop("checked","checked"); $(".checkBox-wrapper>input[data-id='1']").prop("checked","checked");
但是,如果我在我的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"); });
首先,不检查复选框.其次,我的控制台打印出奇怪的结果
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]
打印的选择器Strings看起来很完美.当直接写入chrome控制台时,完全相同的选择器返回DOM元素.然后他们返回这样的对象:
[<input type="checkBox" id="checkBox1" data-id="1">]
什么是n.fn.init [0],以及它返回的原因是什么?为什么我的两个看似相同的JQuery函数返回不同的东西?
解决方法
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"); } }); });
工作小提琴: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库的核心:
var jQuery = function( selector,context ) { return new jQuery.fn.init( selector,context ); };
看起来很熟悉,对吗?现在在jquery的缩小版本中,这看起来应该是这样的:
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.