简体   繁体   English

从html按钮调用javascript

[英]Calling javascript from html button

A quick summary of what I am trying to do. 我正在尝试做的快速摘要。 I am trying to make a webpage that receives a list from my python server using flask. 我正在尝试制作一个使用flask从我的python服务器接收列表的网页。 It then adds each element of the list with a checkbox form. 然后,它使用复选框形式添加列表的每个元素。 After that using javascript I will figure out which checkboxes have been checked and return the string to the flask server. 之后,使用javascript,我将找出已选中的复选框,并将字符串返回到flask服务器。 I've tried to implement it and so far the checkbox list creation works. 我已经尝试实现它,到目前为止,复选框列表的创建已经完成。 I just can't figure out how to call the javascript from the html button. 我只是不知道如何从html按钮调用javascript。 I tried to use onClick= "function" but it doesn't seem to work. 我尝试使用onClick =“ function”,但它似乎不起作用。

{% extends "layout.html" %}
{% block content %}

<!-- create the checkbutton lists -->
  <tr><th>Courses</th></tr>
 <br>
{% for i in class_name %}
  <tr><td>{{i.name.tagline}}</td><td><input       type="checkbox" name="ischecked"></td></tr> 
<br><br>
  {% endfor %}

<!-- checkbox -->
<script type = "text/javascript">
document.getElementById("button").click(getChecks());

// function that finds checked boxes
function getChecks()
{  
    var boxes = document.getElementsByName('ischecked');
    var checkedBox = [];
    // loop through all checkboxes  
    for(var i =0; i < boxes.length; i++)
    {
        if(boxes[i].checked)
        {
            checkedBox.push(boxes[i]);
        }        
        document.getElementById("demo").innerHTML = " " + boxes[i] + " ";
    }
    //  return checkedBox.length > 0 ? checkedBox : null
}
</script>

<div p="demo"></p>
<br>
<input type="button" id ="button" value = "advise" />

<tr><th>endpage</th></tr>
{% endblock %}`

I would first recommend placing your script below the #button button, this way the element in the DOM is loaded first. 我首先建议将脚本放置在#button按钮下方,这样可以首先加载DOM中的元素。 Next onclick is formatted like this in native JavaScript: 接下来的onclick在本机JavaScript中的格式如下:

obj.onclick = function(){ ... };

So you want to format it like this: 因此,您要像这样格式化它:

document.getElementById("button").onclick = function() {
    getChecks();
};

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

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