我有以下HTML表单:
<div id="main">
<form Id="search-form" action="/ViewRecord/AllRecord" method="post">
<div>
<fieldset>
<legend>Search</legend>
<p>
<label for="username">Staff name</label>
<input id="username" name="username" type="text" value="" />
<label for="softype"> software type</label>
<input type="submit" value="Search" />
</p>
</fieldset>
</div>
</form>
</div>
我想在点击alert
字段时显示username
框。这是我的JQuery代码:
$(function() {
$("#username").click(function() {
$.getJSON("ViewRecord/GetSoftwareChoice", {},
function(data) {
alert(data);
});
});
});
由于某种原因,Click
永远不会被解雇;我做错了什么?
答案 0 :(得分:1)
您可能需要focus
事件,因为click
只会在您明确点击该元素时触发:
$(function() {
$("#username").focus(function() {
$.getJSON("ViewRecord/GetSoftwareChoice", {}, function(data) {
alert(data);
});
});
});
除此之外,您可能希望查看Firebug以确保请求成功完成。或者,更好的是,您可以使用较低级别的$.ajax
调用来查看请求是否未完成:
$(function() {
$("#username").focus(function() {
$.ajax({
url: 'ViewRecord/GetSoftwareChoice',
dataType: 'json',
type: 'GET',
success: function(data) { alert(data); },
error: function() { alert('something went wrong!'); }
});
});
});
答案 1 :(得分:1)
您的代码是正确的,应该触发该事件。问题可能在于AJAX调用。在ajax调用之前发出警报以确保这确实是问题。