Javascript代码无效。有谁知道为什么?

时间:2016-10-01 11:23:47

标签: javascript html

正如标题所说,下面的代码并不是真的,我不知道为什么。

Html:

<html>
  <head>

  </head>
  <body>
    <form>
      <input type="textbox" class="probe"></input>
    <button class="probar">h</button>
    </form>
  <p id="pu">h<p>
  </body>
</html>

JS:

    $(document).ready(function(){
//Global variables
  var poste = "";
  var wSearch= "";


 $("probar").on("click",function(){
//Doing a JSON request to wikipedia api
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&format=jsonfm&search=America&namespace=0&limit=10&redirects=resolve&format=json&callback=?", function(data) {
//Triying to get the data returned. It doesn't works.   
  console.log(data); 
});   
  });

});

所以它的功能是,当你点击“probar”按钮时,它会从维基百科API请求一个JSON并将它放入控制台。就这样。它不起作用。

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

您还没有做任何事情来将JavaScript与HTML相关联。您需要<script>元素:

<script src="foo.js"></script>

执行此操作后,您会在浏览器的开发者工具的控制台中看到引用错误,因为未定义$。您需要另一个脚本元素来加载您所依赖的jQuery库。

然后您需要了解selectors

probar是一个类型选择器,它将匹配HTML中不允许的<probar>元素。

类选择器以.

开头

答案 1 :(得分:0)

<强> HTML

<!DOCTYPE html/>
<html>
<head>
 <title></title
 <script src="javascript_file.js"></script>
 </head>
 <body>
 <form>
 <input type="textbox" class="probe"></input>
 <button class="probar">h</button>
 </form>
 <p id="pu">h<p>
 </body>
 </html>

<强>的Javascript

$(document).ready(function(){
//Global variables
var poste = "";
var wSearch= "";


$(".probar").on("click",function(){ // add dot begining class selector
//Doing a JSON request to wikipedia api
$.getJSON("https://en.wikipedia.org/w/api.php?  action=opensearch&format=jsonfm&search=America&namespace=0&limit=10&redirects=resolve&format=json&callback=?", function(data) {
//Triying to get the data returned. It doesn't works.   
 console.log(data); 
 });   
 });

 });

答案 2 :(得分:-1)

<!DOCTYPE html>
<html>
<head>
    <title>form</title>
</head>
<body>
    <input id="txtQuery" type="text" />
    <button id="btnRequest">Request</button>

    <pre id="txtResponse"><pre>
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script>
    $(document).ready(function(){

            $("#btnRequest").click(function(){
                //Doing a JSON request to wikipedia api
                $.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&format=jsonfm&search="+ $("#txtQuery").val() + "&namespace=0&limit=10&redirects=resolve&format=json&callback=?", function(data) {
                    $("#txtResponse").html(JSON.stringify(data,null,4));
                });   
            });
    });
    </script>
</body>
</html>