简体   繁体   English

DOM元素不显示

[英]DOM element doesn't display

I am new in Javascript and I am trying to test following code 我是Java语言的新手,正在尝试测试以下代码

<html>
  <head>
  <script src="jquery/jquery.min.js">
  </head>
<body>
  <input type="button" value="Click button">
  <script type="text/javascript">
  $(function(){
    $('input')[0].on('click',function(){
      alert('button clicked');
    });  
   });
  </script>
</body>
</html>

but when i open this html file in browser the button doesn't display 但是当我在浏览器中打开此html文件时,按钮不显示

Script tags require a closing tag, which you've omitted: 脚本标签需要一个结束标签,您已经省略了它:

<script src="jquery/jquery.min.js"></script>
                                   ^ close

By leaving it open, the browser is treating everything after the script tag as the script content. 通过将其保持打开状态,浏览器会将script标记之后的所有内容都视为script内容。

Also your $('input')[0] isn't right. 另外,您的$('input')[0]是不正确的。 That is getting the DOM element of the input, which has no jQuery wrapper and no .on() function. 那就是获取输入的DOM元素,它没有jQuery包装器,也没有.on()函数。 If you are trying to match just the first input then: 如果您尝试仅匹配第一个输入,则:

$('input').first().on('click',function(){

Problems 问题

  1. Script block must be closed which you missed. 必须关闭您错过的脚本块。
  2. Use $('input') instead of $('input')[0] , When you use $('input')[0] you get DOM element which doesn't have click method. 使用$('input')代替$('input')[0] ,当您使用$('input')[0]会得到没有click方法的DOM元素。

Use 采用

<html>
  <head>
  <script src="jquery/jquery.min.js"></script>
  </head>
<body>
  <input type="button" value="Click button">
  <script type="text/javascript">
  $(function(){
    $('input').on('click',function(){
      alert('button clicked');
    });  
   });
  </script>
</body>
</html>

To avoid these kind of confusions, try to separate like below, 为避免此类混淆,请尝试如下所示进行分离,

In HTML: 在HTML中:

<html>
  <head>
  <script src="jquery/jquery.min.js"></script>
  <script src="main.js"></script>
  </head>
 <body>
   <input type="button" value="Click button">
 </body>
</html>

In main.js 在main.js中

$(function(){ $('input').on('click',function(){ alert('button clicked'); });
});

For Demo 对于演示

继续开发时,添加<!DOCTYPE html>更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM