我知道这是一个基本问题,但我在代码中的某个地方遇到了这个问题。我从某处获取了该代码,但现在我根据需要对其进行修改。
jQuery('#selector') 是做什么的?在我的代码中它总是返回空。
这是我的代码
query: function (selector, context) {
var ret = {}, that = this, jqEls = "", i = 0;
if(context && context.find) {
jqEls = context.find(selector);
} else {
jqEls = jQuery(selector);
}
ret = jqEls.get();
ret.length = jqEls.length;
ret.query = function (sel) {
return that.query(sel, jqEls);
}
return ret;
}
当我调用此查询函数时,我将选择器作为参数传递。当我执行 console.log(selector)
时,它确实拥有我在此函数中需要的所有选择器。但问题出在这一行jqEls = jQuery(selector);
上。当我执行 console.log(jqEls)
后,它返回空,因此整个函数返回空。
我可以使用与此不同的东西来使其工作吗?
最佳答案
jquery('#selector')
相当于 document.getElementById('selector')
。如果没有 id 为 selector
的 DOM 节点,您将得到一个空结果。
例如
<div id="selector">...</div>
将返回与该div对应的dom节点。你有加载jquery吗?
关于javascript - 我的函数返回空。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11934469/