2017-10-12 59 views
0

之前我問我在Stackoverflow關於此問題搜索的問題,並發現我可以禁用或啓用輸入的prop或attr,但當我試圖實現這一點 - 如下面例如 - 它不想切換,我錯過了什麼? 謝謝我怎麼能切換輸入雕像禁用

$(function() { 
 

 
    $('#submit').on('click', function() { 
 
    $('body').prepend('<div class= "item" ></div>'); 
 
    if ($('.item').length > 0) { 
 
     $('#search').removeAttr('disabled'); 
 
    } 
 
    if ($('.item').length == 0) { 
 
     $('#search').attr('disabled', 'disabled'); 
 
     //$('#search').prop('disabled', true); 
 

 
    } 
 

 
    }); 
 

 
    $('#reset').on('click', function() { 
 
    $('.item').remove(); 
 
    }) 
 
});
button { 
 
    display: inline-block 
 
} 
 

 
input { 
 
    position: fixed; 
 
    bottom: 0; 
 
    right: 0 
 
} 
 

 
.item { 
 
    width: 50px; 
 
    height: 50px; 
 
    background: orangered; 
 
    margin: 5px 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type='search' id='search' disabled> 
 
<button id='submit'>Submit</button> 
 
<button id='reset'>Reset</button>

+1

用於禁用搜索欄的代碼應該可以正常工作,但它看起來並不會達到。你使用'item'類注入一個元素,然後檢查class爲'item'的元素的數量是否爲0.它不會是0,因爲你剛剛注入了該類的一個項目。您應該再次查看自己的邏輯,或者提供更多關於您正在嘗試通過與正在單擊的提交按鈕相關的禁用搜索來完​​成的信息。 – mpallansch

+0

當你需要禁用div時不清楚,你能澄清一下你什麼時候需要禁用切換功能? – SilverSurfer

+0

我是新的抱歉,好吧我想要做的是啓用搜索輸入時,身體確實包含div和當div被刪除我想禁用輸入 謝謝 –

回答

1

你不需要檢查所產生的div的lenght,只是有殘疾true或false取決於點擊播放:

$(function() { 
 

 
    $("input").prop('disabled', true); 
 
    $('#submit').on('click', function() { 
 
     $('body').prepend('<div class= "item" ></div>'); 
 
     $("input").prop('disabled', false); 
 
    }); 
 

 
    $('#reset').on('click', function() { 
 
     $('.item').remove(); 
 
     $("input").prop('disabled', true); 
 
    }) 
 
});
button { 
 
    display: inline-block 
 
} 
 

 
input { 
 
    position: fixed; 
 
    bottom: 0; 
 
    right: 0 
 
} 
 

 
.item { 
 
    width: 50px; 
 
    height: 50px; 
 
    background: orangered; 
 
    margin: 5px 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type='search' id='search'> 
 
<button id='submit'>Submit</button> 
 
<button id='reset'>Reset</button>

+0

我確定當我問你關於這個問題你會解決它 –

+0

不客氣=) – SilverSurfer

2

對於你的HTML,使用這個;

<input type='search' id='search' disabled="disabled"> 
<button id='submit'>Submit</button> 
<button id='reset'>Reset</button> 

請注意,[disabled =「disabled」],那麼你的Javascript使用;

<script> 
    (function() { 
     var searchInput = $("#search"); 
     var searchAttr = $("#search").attr("disabled"); 

     $("#submit").click(function() { 
     $('body').prepend('<div class= "item" ></div>'); 
     if ($('.item').length === 0) { // Use triple equals for exact type check 

      searchInput.attr("disabled", searchAttr); 
     } else{ 
      searchInput.removeAttr("disabled"); 
     } 
     }); 

     $('#reset').on('click', function() { 
     $('.item').remove(); 
     searchInput.attr("disabled", searchAttr); 
     }) 
    })(); 
    </script> 

我相信這應該有效。請不要忘記提出這個答案。 :)