I've worked by way through a lot of the questions on the site that are asking the same thing, but I can't
I get the following error in the console window from an onClick event in my code:
1 Uncaught ReferenceError: SetName is not defined
From this line:
$("#lstResults").append("<li><a href='#' onClick='SetName()'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
I've worked my way through Uncaught ReferenceError: $ is not defined?尝试追踪问题,其他几个没有运气。
我试过了:
我真的被困了所以任何帮助都会受到赞赏!
代码:
<head runat="server">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<link href="CSS/jquery-ui-1.12.1.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="CSS/basics.css" rel="stylesheet" />
<link href="CSS/fonts.css" rel="stylesheet" />
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(function () { // this will be called when the DOM is ready
function SetName() {
alert("I hit this!");
}
function findAll(str) {
if (str.length > 2) {
var param = { "searchString": str };
console.log(str.length);
console.log(param);
$.ajax({
type: 'POST',
url: 'adminRightsWebForm.aspx/SearchAppJ',
data: JSON.stringify(param),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (data) {
$("#lstResults").empty();
for (i = 0; i < data.d.length; i++) {
alert(data.d[i].title);
$("#lstResults").append("<li><a href='#' onClick='SetName()'>" + data.d[i].title + "</" + " a>" + "</"
+ "li>");
}
if (data.d.length == 0)
$("#lstResults").empty();
},
error: function (request, status, error) {
alert(request.responseText);
}
});
}
else
$("#lstResults").empty();
}
});
</script> </head>
答案 0 :(得分:7)
这实际上是一个范围问题。
SetName()
函数在$(function(){/* ... */})
匿名函数中定义,但在窗口级别无法访问,onClick
隐式引用。
将函数移到jQuery之上应该解决这个问题。