Javascript代码不工作.有人知道为什么吗?

Javascript code isn't working. Does anyone know why?

本文关键字:为什么 代码 工作 Javascript      更新时间:2023-09-26

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

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); 
});   
  });
});

所以它的假设功能是,当你点击"概率"按钮,它要求从维基百科API的JSON,并把它放到控制台。这是所有。但这行不通。

有谁能帮帮我吗?

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

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

这样做后,您将在浏览器开发人员工具的控制台上看到一个引用错误,因为没有定义$。您需要另一个脚本元素来加载您所依赖的jQuery库。

然后你需要学习选择器

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

类选择器以.

开头

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); 
 });   
 });
 });
<!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>