jQuery 如果输入值等于特定文本,则显示 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22110659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
if input value equals specific text, display div
提问by user3367388
I'm learning jQuery slowly but surely, so please excuse my ignorance. I did a lot of googling that resulted in the Frankenstein example below.
我正在缓慢但肯定地学习 jQuery,所以请原谅我的无知。我做了很多谷歌搜索,导致了下面的弗兰肯斯坦示例。
In this example, if the user enters "Kasey" into the input
, I would like div#pete to have display:block
.
在这个例子中,如果用户在 中输入“Kasey” input
,我希望 div#pete 有display:block
.
Thanks in advance!
提前致谢!
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
var val = $("#fname").length;
if (val = Kasey) {
$("#pete").css("display", "block");
}
</script>
</head>
<body>
<p>Name: <input type="text" id="fname"></p>
<p id="pete" style="display:none;" >Pete</p>
</body>
</html>
回答by Pranav C Balan
You can use keyup()
handler to listen keyup
event. Inside that use this.value
to get the value
您可以使用keyup()
处理程序来监听keyup
事件。里面那个this.value
用来获取值
$(document).ready(function() {
$("#fname").keyup(function() {
if (this.value == "Kasey") {
$("#pete").css("display", "block");
}
else {
$("#pete").css("display", "none");
}
});
});
UPADATE :
更新:
You can simplify the code as follows
您可以将代码简化如下
$(document).ready(function () {
$("#fname").keyup(function () {
$("#pete").css("display", this.value == "Kasey" ? "block" : "none");
});
});
回答by chriz
do this changes to your code
对您的代码执行此更改
- add
val()
for getting value of an element - use
==
operator in condition - for comparing string you should add quotes like "Kasey"
- 添加
val()
以获取元素的值 ==
在条件中使用运算符- 为了比较字符串,你应该添加像“Kasey”这样的引号
Note : if u want do this on form load code like follows or add keyup()
event
注意:如果你想在表单加载代码上执行此操作,如下所示或添加keyup()
事件
<script>
$(document).ready(function(){
var val = $("#fname").val();
if (val == 'Kasey') {
$("#pete").css("display", "block");
}
});
</script>
回答by khaos337
The problem is that your function is reading the value of fname when the document loads and not after the user input. Also, you are assigning the length to val when you should be assigning the value
问题是您的函数在文档加载时而不是在用户输入之后读取 fname 的值。此外,当您应该分配值时,您正在将长度分配给 val
var val = $("#fname").val();
Lastly your if statement needs the is equal to operator with is ==
最后,您的 if 语句需要等于运算符和 is ==
if (val == 'Kasey')