为什么不是';t jQuery为我使用ASP.NET
本文关键字:ASP NET jQuery 为什么不 | 更新日期: 2023-09-27 18:22:08
这不起作用,我也不明白为什么,我在W3schools上尝试过该代码,它起作用了,我认为问题可能是引用或其他什么,我是ASP.NET的新手。
ASP代码(母版页)
<script src="./Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#bt_insertar").click(function () {
alert("Handler for .click() called.");
});
});
</script>
<asp:ContentPlaceHolder id="head" runat="server"></asp:ContentPlaceHolder>
Index.aspx
<td class="style4">
<asp:Button ID="bt_insertar" runat="server" Text="Insertar" Width="71px"
onclick="bt_insertar_Click" style="height: 26px" />
</td>
默认情况下,赋予runat="server"
控件的ID
不是最终出现在DOM元素上的id
。您可以从服务器端控件对象上的ClientID
属性获取ASP.Net生成的ID。例如,更改:
$("#bt_insertar").click(...
至
$("#<%= bt_insertar.ClientID%>").click(...
如果该代码在ASP.Net解析的页面中(与外部JavaScript文件相反)。
从ASP.Net 4开始,您可以通过ClientIDMode
属性控制此行为。例如,如果您使用Static
模式(control.ClientIDMode = CLientIDMode.Static;
),那么ID
实际上是按原样传递的。但ClientIDMode
的默认值是Predictable
,它会修改您使用的ID
。
要将jquery函数绑定到Asp.net服务器控件,必须以这种方式编写代码。
<script type="text/javascript">
$(document).ready(function () {
$('#<%= bt_insertar.ClientID %>').click(function () {
alert("Handler for .click() called.");
});
});
几点:
- 在JQuery include语句中,src应为
src="../Scripts/jquery-1.4.1.js"
,而不是src="./Scripts/jquery-1.4.1.js"
- 您不需要在
document.ready
事件中绑定点击事件,而是可以在asp:Button
中包含OnClientClick="bt_insertar_Click();"
然后你可以定义你的function bt_insertar_Click()
<script type="text/javascript">
function bt_insertar_Click() {
alert("Handler for .click() called.");
}
</script>
更好的编程实践是为您的网页使用一个单独的.js文件,这样您就可以将所有相关的js函数移动到这个js文件中,然后像处理jquery文件一样将其包含在内。