-1
我想搜索數據是否存在於我的對象上,並且此代碼按預期工作,但顯示結果時出現問題。它顯示了我在我的對象上的所有索引。如何停止循環json如果發現數據
如果結果是在我對象
$(document).ready(function(){
\t var myData = {
\t \t "animals":[{
\t \t \t "name":"cat"
\t \t },
\t \t {
\t \t \t "name":"dog"
\t \t },
\t \t {
\t \t \t "name":"horse"
\t \t },
\t \t {
\t \t \t "name":"bear"
\t \t }
\t \t ]};
\t $('#send').click(function(){
\t \t var res = $('#animal').val();
\t \t
\t \t $.each(myData.animals, function(i,j){
\t \t \t if(j.name == res){
\t \t \t \t console.log('found');
\t \t \t }
\t \t \t else{
\t \t \t \t console.log('not found');
\t \t \t }
\t \t });
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myData">
\t <input type="text" id='animal'>
\t <button id='send'>find</button>
</div>
而不是試圖停止循環,使用陣列中的第一元素的值一種更適合任務的方法,如過濾器。 http://api.jquery.com/filter/#filter-elements – Taplar
要打破每個使用'return false;' – Satpal