[英]Use JavaScript to Flag a Word From a List
I'm trying to use javascript to flag a word from a set list but it doesn't seem to be working. 我正在尝试使用javascript从集合列表中标记单词,但是它似乎无法正常工作。 Basically I want the user to be able to type in a word and if it matches any on the list on the right it flags the word in red.
基本上,我希望用户能够输入一个单词,如果它与右侧列表中的任何单词匹配,则将其标记为红色。
Any idea on what I am doing wrong? 有什么想法我做错了吗?
http://jsfiddle.net/Copernicus76/rpuXW/embedded/result/ http://jsfiddle.net/Copernicus76/rpuXW/embedded/result/
// Load the banned plates json data
var platesJson = (function () {
platesJson = null;
$.ajax({
'async': false,
'global': false,
'url': "bannedplates.json",
'dataType': "json",
'success': function (bannedplates) {
platesJson = bannedplates;
}
});
return platesJson;
})();
$(document).ready(function () {
// Draw the list //
$.each(platesJson, function (i) {
$('#plate-list').append('<div class="row-' + i + '">' + platesJson[i].plate + '</div>');
});
// Search the banned plates //
$('#plate-text').keyup(function () {
var result = '';
var plateRow = '';
var scrollPosition;
var searchText = $('#plate-text').val().toUpperCase();
$.each(platesJson, function (i) {
if (searchText == platesJson[i].plate) {
result = 'banned';
plateRow = i;
scrollPosition = i * 19;
}
});
if (/\S/.test(searchText)) {
if (result == 'banned') {
$('#plate-intro,#plate-ok').hide();
$('#plate-banned').show().fadeOut(1500);
$('#plate-text').addClass('banned');
$('#plate-list').animate({
scrollTop: scrollPosition
}, 1000);
$('#plate-list div.row-' + plateRow + '').addClass('banned');
} else {
$('#plate-intro,#plate-banned').hide();
$('#plate-ok').show().fadeOut(1500);
$('#plate-text').removeClass('banned');
}
} else {
$('#plate-text').val('');
$('#plate-ok,#plate-banned').hide();
$('#plate-intro').show();
}
});
}); // end document ready
var platesJson = (function () {
platesJson = null;
$.ajax({
'async': false,
'global': false,
'url': "bannedplates.json",
'dataType': "json",
'success': function (bannedplates) {
platesJson = bannedplates;
}
});
return platesJson;
})();
That's not how ajax works. 那不是ajax的工作方式。 The first
a
means asynchronous
, so the success function will run whenever the response comes back. 第
a
表示asynchronous
,因此成功函数将在响应返回时运行。 That doesn't happen immediately, it could take a few minutes or it could fail totally. 这不会立即发生,可能要花几分钟,甚至可能完全失败。 The
success
method is a callback . success
方法是回调 。 That's where you want to do the magic. 那是您想要做魔术的地方。
$.ajax({
'async': false,
'global': false,
'url': "bannedplates.json",
'dataType': "json",
'success': function (bannedplates) {
$.each(bannedplates, function (i) {
$('#plate-list').append('<div class="row-' + i + '">' + bannedplates[i].plate + '</div>');
});
$('#plate-text').keyup(function () {
// ...the rest of your code
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.