如何在 asp.net 网络表单中启用javascript

本文关键字:表单 启用 javascript 网络 net asp | 更新日期: 2023-09-27 17:55:08

我正在尝试在 asp.net 网络表单中使用JavaScript事件。 但是输入控件(如文本字段)的事件(如 onClick、onFocus、onBlur)不会出现。 我需要更改我的指令吗:

<%@ Page Title="" Language="C#" MasterPageFile="~/YourGuruMaster.master" AutoEventWireup="true" CodeFile="AskQuestion.aspx.cs" Inherits="AskQuestion" %>

我希望能够做到这一点:

//code page
    protected void Page_Load(object sender, EventArgs e)
{
    QuestionTextBox1.Attributes["onfocus"] = "ClearSearchText()";
//Markup page
     function ClearSearchText() {
        var searchUserName = document.getElementById('<%=QuestionTextBox1.ClientID%>');
        if (searchUserName.value = searchUserName.defaultValue) {
            searchUserName.value = "";
        }

        return false;
    }
<p dir="rtl" style="">
<asp:TextBox ID="QuestionTextBox1" runat="server" Width="702px" 
Text="פרטים עד 5000 תווים"></asp:TextBox>

如何在 asp.net 网络表单中启用javascript

onfocusonblur添加到标记中,如下所示:

<asp:TextBox ID="TextBox1" runat="server" onfocus="TextBox1_focus(this, event)" onblur="TextBox1_blur(this, event)" Text="Search..."></asp:TextBox>
<script type="text/javascript">
    var searchText = 'Search...';
    function TextBox1_focus(sender, e) {
        if (sender.value == searchText)
            sender.value = '';
    }
    function TextBox1_blur(sender, e) {
        if (sender.value == '')
            sender.value = searchText;
    }
</script>

好吧,不确定您使用哪个 ASP.NET 版本。我认为最新版本允许这样做(服务器控件仍然无法理解浏览器的渲染属性)。尝试使用"对焦"代替(小写)。

但是,如果这对您不起作用,那么您必须从代码隐藏中执行此操作......

protected void Page_Load(object sender, EventArgs e)
{
    QuestionTextBox1. Attributes["onfocus"]="someJavaScriptMethod";
}

或者,如果你在页面中有jQuery,你可以像...

<script type="text/javascript">
$(function() {
    $('#<%= QuestionTextBox1.ClientID %>').focus(someJavaScriptMethod);
});
</script>

如果这样做,在 someJavaScriptMethod() 中,您可以使用单词 this 指向焦点控件,并且可以轻松地从中创建 jQuery 对象,如 $(this)

.

如果以上都不能解决您的问题,请给我留言。