2017-04-24 196 views
0

我使用awesomplete autocomplete plugin與縮略圖和我的index.html,我已經<input id="myinput">元素,但在我的laoyut.html,如果我沒有把<input id="myinput">然後JS給我這個錯誤回報 jquery.min.js:2 Uncaught TypeError: Cannot read property 'offsetWidth' of undefined如何解決未定義錯誤的offsetWidth?

和我的問題我應該怎麼做才能解決這個問題?

var input = document.getElementById("myinput"); 
 

 
// Show label but insert value into the input: 
 
new Awesomplete(input, { 
 
    list: [{ 
 
     label: "<img src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRUxdD-Q4nIx3uIg9jBCe1oT5a9MHuWY5_pW4FoZSU-nQd1Y_WJPQ'/> Faceboock", 
 
     value: "https://www.facebook.com/" 
 
    }, 
 
    { 
 
     label: "<img src='https://hydra-media.cursecdn.com/dota2.gamepedia.com/thumb/2/25/Pounce_icon.png/16px-Pounce_icon.png?version=77c984fc4a9c8ca491ead081322fa738'/> Youtube", 
 
     value: "https://www.youtube.com/" 
 
    }, 
 
    { 
 
     label: "China", 
 
     value: "CN" 
 
    }, 
 
    { 
 
     label: "United States", 
 
     value: "US" 
 
    } 
 
    ] 
 
}); 
 

 
// You can search for a better version 
 
$(document).find('.awesomplete').on('click', function(e) { 
 
    if ($('#myinput').val()) 
 
    window.location = $('#myinput').val(); 
 
    //console.log($('#myinput').val()); 
 
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.css" rel="stylesheet"/> 
 
<input id="myinput" /> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.js"></script>

回答

1

你可以先檢查是否#myinput是在HTML DOM可用,那麼你可以使用它的價值。

var input = $("#myinput"); 
if (input.size() > 0) { 
    window.location = input.val(); 
} 

我推斷會有一個具有此特定ID的div。在這種情況下,你可以使用

if (input.size() === 1) { 

因此,在短期,你可以用

$(document).find('.awesomplete').on('click', function(e) { 
    var input = $('#myinput'); 
    if (input.size() === 1) { 
    window.location = input.val(); 
    } 
}); 
+0

感謝取代

$(document).find('.awesomplete').on('click', function(e) { if ($('#myinput').val()) window.location = $('#myinput').val(); //console.log($('#myinput').val()); }); 

這樣怎能aplly呢? –

+0

是的,但我仍然得到這個錯誤和新的錯誤太未捕獲TypeError:無法讀取屬性'setAttribute'null –

+0

我更新了答案,讓我知道如果這適用於你 – Bram

相關問題