Javascript 我可以在按钮上附加动作吗?

Javascript 我可以在按钮上附加动作吗?,javascript,html,button,Javascript,Html,Button,如果我有一个按钮,我可以附加一个操作来执行服务器端处理,还是必须将其包装成一个表单 比如说 <button type="submit" onClick="listco_directory_contents.js"> List </button> 列表 这是否可行,或者是否需要表格 你不能有一个type=“submit”如果它不是在表单中,那么就没有东西可以提交。您可以做的是创建一个,然后将一个事件附加到它: var myButton = document.select

如果我有一个按钮,我可以附加一个操作来执行服务器端处理,还是必须将其包装成一个表单

比如说

<button type="submit" onClick="listco_directory_contents.js"> List </button>
列表

这是否可行,或者是否需要表格

你不能有一个
type=“submit”
如果它不是在表单中,那么就没有东西可以提交。您可以做的是创建一个
,然后将一个事件附加到它:

var myButton = document.selectElementById('myButton');
myButton.addEventListener('click', function() {
  /* do something cool */
}, false);

“做一些很酷的事情”可能是一个Ajax请求,因此您可以向服务器发送数据。

您可以这样做,但如果您的目标是做服务器端处理,我建议使用jquery方式

<!--this button uses javascript-->
<input type="button" onclick="myfunction()" value="button"/>

<!--this button uses jquery-->
<input type="button" id="myfunction" value="button"/>

<script>
//javascript function using the onclick event
function myfunction(){
    alert("an action");
    // or any other function u wish to 
    // do once the button is click
}

//jquery using the id of the button
$(document).ready(function(){  
    $("#myfunction").click(function(){
        alert("another action");
        // or any other function u wish to 
        // do once the button is click
    });
});
</script>

//使用onclick事件的javascript函数
函数myfunction(){
警惕(“行动”);
//或任何其他你想要的功能
//单击按钮后执行此操作
}
//使用按钮id的jquery
$(文档).ready(函数(){
$(“#我的函数”)。单击(函数(){
警惕(“另一行动”);
//或任何其他你想要的功能
//单击按钮后执行此操作
});
});
也可以是type=submit

$(function(){
 $('input[type="submit"]').on('click',function(){
  alert('hi');
 })
})

您也可以只包含js:

<script type="text/javascript" src="listco_directory_contents.js"></script>

然后从那里调用所需的任何函数:

<button onClick="exampleFunction()"> List </button>
列表
或者,如果您想使用php进行服务器端处理,您可以简单地执行以下操作:

<button onClick="$.post('http://example.com/index.php');"> List </button>
列表
<button onClick="$.post('http://example.com/index.php');"> List </button>