我正在制作REST api,正在开发一些javascript函数。
这里的想法是运行例如:$('#main').get('car/ford');
,返回的数据将添加到提供的元素中。
这是所有的javascript:
$.fn.extend({
get: function (path) {
request(this, 'GET', path);
}
});
function request(element, type, path) {
var dees = $(element);
$.ajax({
type: type,
url: '/request/'+path,
success: function(data) {
console.log('Success');
a = $(element);
b = $('#fileList'); // this is a control
dees.html(data);
}
});
}
(function() {
console.log('running');
$('#fileList').get('car/ford');
})();
我遇到的问题是,当我运行
a.html(data);
一切都不会改变。但是如果我运行
b.html(data);
一切正常。
因此,这两个选择器之间存在差异。
在上找不到元素a.length == 0
在b上找到元素b.length == 1
为什么选择器找不到该元素,我该如何解决?
最佳答案
通过在调用函数前面添加$可以解决此问题。
从:
(function() {
console.log('running');
$('#fileList').get('car/ford');
})();
至:
$(function() {
console.log('running');
$('#fileList').get('car/ford');
});