【问题标题】:How to call jJavascript function from code behind on button click in asp net C#?如何在asp net C#中单击按钮时从代码后面调用javascript函数?
【发布时间】:2019-07-30 01:11:31
【问题描述】:

这是我的 Javascript 函数:

<script type="text/javascript">

    function SelectionTextBox()
    {

            document.getElementById("TextBox1").select();

    }

</script>

这里我调用按钮上的函数:

ScriptManager.RegisterClientScriptBlock(this, GetType(), "t ", "SelectionTextBox();", true);

我想在单击按钮时选择 TextBox1 中的文本,但它不起作用。

【问题讨论】:

  • 使用focus()函数
  • 这些控件是在另一个用户控件还是母版页中?

标签: javascript c# asp.net dom-events


【解决方案1】:

var selectButton = document.getElementById("mySelectBtn");
var textBox = document.getElementById("myTextBox");
selectButton.addEventListener('click', SelectionTextBox = function(){

textBox.focus();
textBox.select();

});
<input type='button' id='mySelectBtn' value='Select'/>
<input type='text' id='myTextBox' value='testString'/>

尝试使用此代码通过 Code behind (C#) 处理 Javascript 函数:

Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction","SelectionTextBox();",true);

改为:

ScriptManager.RegisterClientScriptBlock(this, GetType(), "t ", "SelectionTextBox();", true);

JavaScript 应该是:

var input = document.getElementById('myTextInput');

input.focus();
input.select();

【讨论】:

  • @DemenyiNorbert 我已经编辑了我的解决方案,请检查一下.. 你应该使用 focus() 函数
  • @DemenyiNorbert 试试这个:stackoverflow.com/questions/18931936/…
  • 抱歉,我在发布我的问题之前尝试了这个。我无法意识到问题所在。我尝试了使用按钮的 alert() 方法,但选择不起作用。
  • @DemenyiNorbert 这是一个适用此方法的示例:jsfiddle.net/5mad9dpr 所以,我也在上面编辑了我的解决方案
  • 这工作正常,但是当我使用 onclick="Button1_Click" 时的问题可以t call C# codes, &lt;input type='button' id='Button1' onclick="Button1_Click" /&gt;. Therfore I would like to use &lt;asp:Button ID="Button1" instead of &lt;input type='button' but this way cant 调用 javascript 函数。
【解决方案2】:

你得到了这个,因为你的脚本是在你的控件被渲染之前被执行的。只需使用RegisterStartupScript 即可。

RegisterStartupScript 将在关闭 form 标记之前编写您的脚本,因此您在那里会很安全。

ScriptManager.RegisterStartupScript(this, GetType(), "t ", "SelectionTextBox();", true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多