首页 > 解决方案 > 如何使用 javascript 从 ASP.NET 按钮获取 url 地址

问题描述

我想使用 javascript 从 ASP.NET 按钮获取 PostBackUrl 值,但这似乎是不可能的,因为 onclick 属性具有嵌入 url 地址的 javascript 代码。

这是我在 Chrome F12 调试器中看到的:

<input type="submit" name="btnGroceryShelve" value="Grocery Shelve"
 onclick="javascript:WebForm_DoPostBackWithOptions(
new WebForm_PostBackOptions(
&quot;btnGroceryShelve&quot;, &quot;&quot;, false, &quot;&quot;, 
&quot;https://www.grocerystore.com/&quot;, false, false))" 
id="btnGroceryShelve">

这是asp.net代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" 
    Inherits="TestApp.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test</title>
    <script src="Scripts/jquery-3.6.0.min.js"></script>

    <script type="text/javascript">
        function GetAddress() {
            var address = $("#btnGroceryShelve").attr('onclick');
            alert("this address is " + address);
        }
        
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <button type="button" onclick="GetAddress()">Get Address</button>
            <asp:Button ID="btnGroceryShelve" ClientIDMode="Static" 
runat="server" Text="Grocery Shelve" 
PostBackUrl="https://www.grocerystore.com/"/>
        </div>

    </form>
</body>
</html>

是否可以在 javascript 中提取 PostBackUrl 值?

标签: asp.net

解决方案


添加ClientIDMode="Static"到您<asp:Button>的标记中,它将在您的标记中包含 id 'btnGroceryShelve'。


推荐阅读