嗨,我是 JavaScript 的新手,非常感谢任何帮助或建议。
我希望我的两个 textfield 可见。
我下面的代码仅适用于没有分号的单个变量,但有时如果有多个变量则使用分号我只是想知道它是否可能我真的很感激建议。
var comp = "apple";
$( document ).ready(function() {
var comp = "apple";
$('#txt1').hide();
$('#txt2').hide();
$('#txt3').hide();
if (comp == "apple"){
$('#txt1').show();
}
});
但是如果
var comp = "apple;ice;grapes";
由于 apple 和 grapes 在变量中,apple 和 grapes 应该是可见的。
最佳答案
如果操作数相等,
==
返回 true。显然,"apple;ice;grapes"!= "apple"
。
您可以使用 String.prototype.includes()
:
The
includes()
method determines whether one string may be found within another string, returning true or false as appropriate.
请注意:您可以将多个 id 作为选择器的一部分传递给 hide() 它们。但最好尽可能使用 CSS 来设置样式。
$( document ).ready(function() {
var comp = "apple;ice;grapes";
//$('#txt1,#txt2,#txt3').hide();
if (comp.includes("apple") && comp.includes("grapes")){
$('#txt1, #txt2').show();
}
});
#txt1,#txt2,#txt3{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="txt1">apple</div>
<div id="txt2">grapes</div>
<div id="txt3">ice</div>
关于javascript - 基于其他值的文本字段的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53512939/