首先让我开始说,在 Web 开发方面,我就像是从水里捞出来的鱼。我是一名 C/C++、Labview 开发人员,从未接触过 HTML、JQuery 代码。
我开发了一个记录器来在 HTML 文件中显示错误、警告和其他信息。我已经成功地编写了 JQuery 代码来根据按钮点击显示/隐藏 div。例如;错误按钮仅以红色字体等显示错误。
现在我正在尝试引入一个文本框,它会根据文本值显示/隐藏 div。我实现了一些代码但没有工作。 这是代码;
<button id="showError">Show Error</button>
<button id="showDebug">ShowDebug</button>
<button id="showAll">Show All</button>
<input type="text" name="keywords">
<script>
$("#showError").click(function () {
$('div[id^="error"]').show();
$('div[id^="debug"]').hide();
});
$("#showDebug").click(function () {
$('div[id^="error"]').hide();
$('div[id^="debug"]').show();
});
$("#showAll").click(function () {
$('div[id^="error"]').show();
$('div[id^="debug"]').show();
});
// this is where i need the help! I can't
// the regular expression to execute.
$('.keywords').keyup(function() {
var value = $(this).val();
var exp = new RegExp('^' + value, 'i');
$('div[id^="error"]').each(function() {
var isMatch = exp.test($(this).text());
$(this).toggle(isMatch);
});
});
// End of problem
</script>
<div style="color: rgb(51, 51, 255);" id="error">20140124_145317 - MainLoop: LoadTestStationConfiguration </div>
<div style="color: rgb(51, 51, 0);" id="debug">20140124_145338 - MainLoop: ReadConfigData </div>
<div style="color: rgb(51, 51, 255);" id="error">20140124_145338 - SecondLoop: CheckForNewSoftwareVersion </div>
因此,如果输入文本值 = SecondLoop,则只会显示最后一个 div 元素。如果输入文本值 = MainLoop,则将显示前 2 个元素。
感谢您花时间阅读本文,再说一遍,这是我第一次在浏览器中编程! (与 C++ 如此不同;))
最佳答案
$('.keywords')
选择器使用错误,改成这个
$('input[name=keywords]')
关于javascript - 根据输入字段中的文本隐藏/显示 div 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21324693/