2016-04-25 51 views
0

如何在jQuery的javascript下實現多個功能?如果我刪除第二個函數(它實際上在我的Eclipse項目中工作,出於某種原因,如果我在這裏刪除第二個函數,它不工作),「獲取項目」按鈕工作正常。更改標籤時,點擊下拉列表中的jquery javascript

我想在這裏實現兩件事: 1)單擊「獲取項目」,將項目添加到下拉列表中。 2)從列表中選擇不同的項目時,標籤將根據所選內容更改文本。

$(document).ready(function() { 
 
     $('#projectbutton').click(function() { 
 
     var selector = document.getElementById('projectselector'); 
 
     var api = "http://localhost:8080/restapi/test/projects"; 
 
     $.getJSON(api, {"1":"project 1", "2":"project 2"},function (data) { 
 
      $.each(data, function (index, d) { 
 
       selector.options[selector.options.length] = new Option(d,d); 
 
      }); 
 
     }); 
 
     }); 
 
}); 
 
$(document).ready(function() { 
 
    $('#projectselector').change(function() { 
 
     var text = $('option:selected',this).text(); 
 
     $('#selectedprojectname').text(text); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="firstsection"> 
 
    <h1>List project</h1> 
 
    <button id="projectbutton" name="projectbutton">Get Projects</button> 
 
</div> 
 
<div id="secondsection"> 
 
    <h2>All available projects:</h2> 
 
    Projects: <select id="projectselector" name="projectselector"></select> 
 
</div> 
 
<div id="thirdsection"> 
 
    <h3>Selected project:</h3> 
 
    <label id=selectedprojectname name="selectedprojectname">empty</label> 
 
</div>

回答

0

我不知道你想在getJSON電話做什麼。第二個參數只是發送到API調用的數據,所以您可能不需要傳遞的內容。

在任何情況下,API調用都有問題。如果你刪除它的API部分的作品。

http://jsfiddle.net/CnEUh/3137/

$(document).ready(function() { 
    $('#projectbutton').click(function() { 
    var selector = document.getElementById('projectselector'); 
    var api = "http://localhost:8080/restapi/test/projects"; 
    var data = {"1":"project 1", "2":"project 2"}; 
     $.each(data, function (index, d) { 
     selector.options[selector.options.length] = new Option(d,d); 
     }); 
    }); 

    $('#projectselector').change(function() { 
    var text = $('option:selected',this).text(); 
    $('#selectedprojectname').text(text); 
    }); 
}); 

你的jQuery看起來不錯,但我可以,除非你發佈API代碼不再與API調用幫助。

+0

感謝您的快速回答。我沒想到會是導致問題的api調用。我認爲這是導致它的多種功能。 –

相關問題