[英]button click is not working inside jquery
我是 html 和 java 腳本的新手。 我嘗試創建一個按鈕並從 URL 獲取 JSON 並將結果添加到下拉列表中。 在 Nodejs 服務器啟動並運行后,如果您輸入http://localhost:8080/restapi/test/projects ,它將返回 {example} 作為結果。
所以這里有幾個問題:1)出於某種原因,按鈕單擊在 jquery 中不起作用 2)$.getJSON 只能在 jquery 中使用,還有其他方法可以從 URL 響應中獲取 JSON 嗎?
$(document).ready(function () { $(document).on('click', '#button1', function() { var selector = document.getElementById('selector'); var api = 'http://localhost:8080/restapi/test/projects'; $.getJSON(api, function (data) { $.each(data, function (index, d) { var option = document.createElement('option'); option = d; selector.add(option); }); }) }) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <div id='first'> <h1>project options</h1> <button id='button1'>Get Projects</button> </div> <div id='second'> <h2>all projects</h2> Projects: <select id='selector'></select> </div>
感謝您提供任何提示。
{example}
不是有效的 JSON。 試試{"1":"example"}
另外, option = d
; 將覆蓋您的選項。 試試option.value = d;
這是一個清理過的版本給你:
$(document).ready(function () {
$('#button1').click(function() {
var selector = document.getElementById('selector');
var api = 'http://localhost:8080/restapi/test/projects';
$.getJSON(api, {"1":"example","2":"other example"},function (data) {
$.each(data, function (index, d) {
selector.options[selector.options.length] = new Option(d,d);
});
});
});
});
請嘗試以下操作:
$(document).ready(function () {
$('body').on('click', '#button1', function() {//this sintax is used most for dynamically added elements
var selector = $('#selector');
var api = 'http://localhost:8080/restapi/test/projects';
$.getJSON(api, function (data) {
$.each(data, function (index, d) {
var option ='<option>'+d+'</option>';
selector.append(option);
});
})
})
})
它不會起作用,因為您沒有執行單擊的確切操作。您所做的只是$(document).click()
不知道要單擊哪些元素或文檔。
你應該用過
$('#button1').on('click',function() {
});
用於按鈕單擊,它告訴它只有在單擊按鈕時才會響應。為了您更好地理解,我給出了代碼片段
$(document).ready(function () { $('#button1').on('click',function() { var selector = document.getElementById('selector'); var api = 'http://localhost:8080/restapi/test/projects'; $.getJSON(api, function (data) { $.each(data, function (index, d) { var option = document.createElement('option'); option = d; selector.add(option); }); }); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <div id='first'> <h1>project options</h1> <button id='button1'>Get Projects</button> </div> <div id='second'> <h2>all projects</h2> Projects: <select id='selector'></select> </div>
它會工作。如果沒有,請檢查您的 api 網址。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.