如何通过简单的 if 条件语句将 div 可见性与输入文本链接



我想通过非常简单的 if 条件语句将两个 htmldiv 的可见性与输入是否有值联系起来,但我可能有问题。

.html:

<input id="tags" />
<div id="div1" >
this is first div means input don't have value values
</div>
<div id="div2" >
this is second div means input does have value.
</div>

脚本:

$('#tags').on('keyup',function(e){
var div1 =  $('#div1');
var div2 =  $('#div2');
var txt=$(this).val ;
if (txt.length == 0){
div1.hide();
div2.show();
} else {
div1.show();
div2.hide();
}  
});

它仅在我第一次输入时有效。 谁能帮我?

使用这个:

var txt=$(this).val() ;

而不是

var txt=$(this).val ;

请参考 jQuery 文档来正确使用 val(( 函数。

错误:无效的 jquery 对象更改为val()而不是val。并验证 length.use withtrim()以删除不需要的空间,否则它也将被计算为空白空间

$('#tags').on('keyup', function(e) {
var div1 = $('#div1');
var div2 = $('#div2');
var txt = $(this).val().trim().length;
if (txt.length == 0) {
div1.hide();
div2.show();
} else {
div1.show();
div2.hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="tags" />
<div id="div1">
this is first div means input don't have value values
</div>
<div id="div2">
this is second div means input does have value.
</div>

使用$(this).val().length

<input id="tags" />
<div id="div1" >
this is first div means input don't have value values
</div>
<div id="div2" >
this is second div means input does have value.
</div>

$('#tags').keyup(function() {
// If value is not empty
if ($(this).val().length == 0) {
div1.hide();
div2.show();
} else {
div1.show();
div2.hide();
}
}).keyup(); // Trigger the keyup event on page load
$(function(){
$('#tags').on('keyup',function(e){
var div1 =  $('#div1');
var div2 =  $('#div2');
var txt=$(this).val() ;
if (!txt.length){
div1.show();
div2.hide();
} else {
div1.hide();
div2.show();
}
});
});
// Declaring outside of the functions speeds up the page because it prevents 
// jQuery from parsing the hole html document again.
var div1 = $('#div1');
var div2 = $('#div2');
// Declare the function outside of jQuery so that we can init the fields
function handleKeyup(event) {
var content = event.target.value;
if (content.length !== 0) {
div1.hide();
div2.show();
return;
}
div1.show();
div2.hide();
}
// Call the function with no data to init the div fields
handleKeyup({ target: { value: '' } });
// Register the keyup listener
$('#tags').on('keyup', handleKeyup);

希望对您有所帮助。这是一笔工作代码:https://codepen.io/flasd/pen/mMXYMa

最新更新