我想知道为什么会这样:
$('#clientSearchFirstName').keyup(runLiveSearch);
但这不是:
$('#clientSearchFirstName').keyup(function() {
runLiveSearch();
});
后者返回的错误与 jQuery 库有关(我有缩小版本),显然以某种方式受到影响:
TypeError: f.nodeName is undefined (jquery.js)
...,h=h.slice(c.length),c.type=g,c.matches=d);if(!c)break}return b?h.length:h?bc.er...
是否无法使用事件处理程序的“默认”函数调用另一个函数?作为引用(我不明白为什么它与函数的内容有关),这是函数:
function runLiveSearch() {
var search_string = $(this).val();
var which = this.id;
which = which.replace("clientSearch","");
if (search_string == '') {
$("#statusBox").fadeOut();
}else{
$.ajax({
url: "echoSearchResults.php?searchQuery=" + search_string + "&which=" + which, // ...etc
type: 'GET',
dataType: 'json',
success: function(data) {
var filler = '';
if (data && data.length > 0) {
if (data.length < 30) {
filler = '<span class="searchInfo">Found '+data.length+' results for "'+search_string+'":</span> <br />'; }
else { filler = '<span class="searchInfo">Showing first 30 results for "'+search_string+'":</span> <br />'; }
filler = filler + '<table id="search-results" cellpadding="2" border="1" cellspacing="1"><tr><td>ID</td><td>First name</td><td>Last Name</td><td>Cell phone</td><td>Home phone</td><td>Work phone</td><td>Primary Phone</td></tr>';
for (x=0;x <= (data.length - 1);x++)
{
filler = filler +'<tr class="searchLink" id="csr'+data[x][0]+'" onclick="displayClientData(this.id); scrollTo(this.id)"><td>'+data[x][0]+'</td><td>' + data[x][1] + '</td><td>' + data[x][2] + '</td><td>'+convertphone(data[x][3],"touser")+'</td><td>'+convertphone(data[x][4],"touser")+'</td><td>'+convertphone(data[x][5],"touser")+'</td><td>'+convertphone(data[x][6],"touser")+'</td></tr>';
}
filler = filler + '</table>';
} else { filler = 'No search results found for "'+search_string+'".'; }
document.getElementById('statusBox').innerHTML = filler;
}
});
$("#statusBox").fadeIn();
}
}
最佳答案
简而言之:将代码更改为
$('#clientSearchFirstName').keyup(function() {
runLiveSearch.call(this);
});
更详细一点:当函数“按原样”调用时,上下文 (this
) 有所不同,而 jQuery 使用 call
方法为函数提供正确的对象。您可以通过记录 this
的值来对此进行试验。
关于javascript - jQuery:在事件处理程序的无名函数中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23716138/