【发布时间】:2012-04-14 23:07:15
【问题描述】:
以下代码执行时遇到的问题,它将首先显示文本框的原始内容,然后是我按下的每组键,直到按下“Enter”。因此,如果文本框最初包含“Ice Cream - Pierre's Chocolate Chip”,然后我单击文本框以获取焦点并将其替换为“Tea”,我将获得 4 个警报框,每个框都有以下内容:
- 冰淇淋 - 皮埃尔的巧克力片
- T
- 特
- 茶
然后,如果我点击不同的行并执行其他操作,我会得到原来的 4 个警告框,然后是新的……它一直在堆积,我不知道为什么?
这是我的 .cs 文件中的一些代码 - 请注意我添加的“OnKeyPress”属性:
public TCell(String celltext,String strTextBox,String strName)
{
int iWidth = 0;
int intRandom =
iWidth = Convert.ToInt32(strTextBox);
tblCell = new TableCell();
TextBox txtItem = new TextBox();
txtItem.ID = strName;
txtItem.Text = celltext;
txtItem.Width = iWidth;
txtItem.BorderStyle = BorderStyle.None;
txtItem.CssClass = "cssAdjust trans";
txtItem.Style.Add("padding", "0px 5px 0px 5px");
txtItem.Attributes.Add("onKeyPress","captureTable(this.value);");
txtItem.Attributes.Add("onFocus", "javascript:this.select();");
tblCell.Controls.Add(txtItem);
}
然后这是我按下回车键后显示的功能:
function captureTable(strValue)
{
$(document).keypress(function (e) {
if (e.which == 13) // Enter has been pressed.
{
e.preventDefault();
document.getElementById("<%=HiddenField1.ClientID %>").value = strValue;
alert(strValue);
}
});
提前感谢您能给我的任何帮助。我使用“window.event”进行了这项工作,但这将我锁定在 IE 中,而我正在尝试为此使用 JQuery。
(更新):
好的,我使用了下面 kmb385 提供的代码,但我想我仍然缺少一些东西。我没有出现任何警报,所以我在 '$(".txtHook").keypress(function(e){' 行设置了一个断点,并且在表格文本框内的键输入期间它没有到达它,包括回车键。
这里是代码在 default.apsx 页面中的位置:
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript">
$(document).ready(function(){
$(".txtHook").keypress(function(e){
if (e.which == 13) // Enter has been pressed.
{
e.preventDefault();
document.getElementById("<%=HiddenField1.ClientID %>").value = $(this).val();
alert(strValue);
}
});
});
我将 JQuery 包含在网站母版页的正文标记中:
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
<Scripts>
<asp:ScriptReference Path="~/Scripts/jquery-1.4.1.min.js" />
</Scripts>
</asp:ScriptManager>
(最终更新:)
原来我包含的 JQuery 是不正确的。我把它移到母版页的head标签上,把代码改成了:
<script type="text/javascript" src="../scripts/jquery-1.4.1.min.js"></script>
之后,我的 kmb385 提供的代码开始工作:)
【问题讨论】:
-
您是想在输入字段获得焦点时按回车键捕获,还是在他们按回车键时捕获?
-
在按下回车键时哪个文本框具有焦点。如果他们按下回车键并且焦点是他们刚刚选择的单选按钮,我希望忽略它。我的屏幕由 2 个下拉列表、一个表格、3 个单选按钮和各种标签组成,这些标签根据表格中的选定行显示信息。我正在使用警报来测试我的逻辑,以捕获键入文本框的内容。谢谢。
-
好的,这有助于我回答你的问题。
-
太棒了!谢谢谢谢!我在上面的评论中添加了更多内容,只是为了更好地描绘我的布局,如果这有任何帮助的话。
标签: jquery