在按钮的onclick事件上将字符串传递给JavaScriptFuntion

Pass string to JavaScript Funtion on onclick event of a button

本文关键字:字符串 JavaScriptFuntion 按钮 onclick 事件      更新时间:2023-09-26

我想在按钮的onclick事件上传递一个值,这样javascript就可以更新隐藏字段的值。但我无法将字符串传递给js函数

JS-

<script>
   function sethdnfiletype(filetype)
   {
       $("#hdnfiletype").val(filetype);
   }
</script>

HTML

<asp:ImageButton ID="btn1" runat="server" ToolTip="Upload Report"  OnClick="sethdnfiletype(// here I want to send a number like 1 or 2 or 3 //);" href="#uploadTOEFilePopup" data-toggle="modal" ClientIDMode="Static">

您可以使用onclick将值发送到函数,只需像通常调用函数一样将它们传入即可。

function clickHandler(amount) {
  alert('Clicked with ' + amount);
}
<button type="button" onclick="clickHandler(123);">Click me</button>

您可以使用绑定。Bind允许您设置一些默认参数和this上下文。所以你可以这样做:sethdnfiletype.bind(this, 1);,它会将值1作为第一个参数传递给你的函数,将事件作为第二个参数。