简体   繁体   English

javascript函数和html onclick属性

[英]javascript function and html onclick property

I am trying to implement a javascript on my page and I want to refer to a function with the onclick property. 我正在尝试在页面上实现JavaScript,我想使用onclick属性引用一个函数。 How would I do this, how would I change my following code so that is actually runs the script correctly? 我将如何执行此操作,如何更改以下代码,以便实际上可以正确运行脚本?

 $(document).ready(function() { function dosomething() { alert('I just did something'); } }); 
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> <input type="button" class="btn btn-default" value="Kortingscode" onclick="dosomething()"> 

Thanks in advance. 提前致谢。

在全局范围内将dosomething函数移至ready函数之外

An other solution is adding the event to the button on the document.ready 另一种解决方案是将事件添加到文档上的按钮。

 $( document ).ready(function() { var button = document.getElementsByClassName("btn")[0]; button.onclick=function(){ alert('Hi'); }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="button" class="btn btn-default" value="Kortingscode"> 

Why are you using document ready event? 为什么使用文档准备事件?

You have two different solution: 您有两种不同的解决方案:

ONE: declare your function as global (outside document ready) 一个:将您的函数声明为全局函数(外部文档已准备好)

function dosomething() {
 alert('I just did something');
}

TWO: declare your function as jquery event 二:将函数声明为jquery事件

$(document).ready(function() {
  $( ".btn-default" ).click(function() {
    alert('I just did something');
  })
)};

Make sure your javascript code is inside a <script></script> tag. 确保您的JavaScript代码在<script></script>标记内。

You can easily use jquery for that. 您可以轻松地使用jquery。

First load the jquery script. 首先加载jQuery脚本。

<script   src="https://code.jquery.com/jquery-1.12.2.min.js""></script>

Then 然后

<input type="button" class="btn btn-default Kortingscode" value="Kortingscode">

The jquery: jQuery的:

   <script>
    $(".Kortingscode").click(function(){
        alert("The button was clicked.");
    });
   </script>

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

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