簡體   English   中英

如何在JavaScript的確認功能中添加字符串值

[英]How to add string value in confirm function of JavaScript

我的asp按鈕中有JavaScript函數。

<asp:Button ID="btnCommission" runat="server" Text="Deposit Commission" OnClientClick="if (!confirm('Are you sure you want to deposit commission into points?')) return false;" OnClick="btnCommission_Click" />

但是我想在我的確認函數中將<%= (commission_total)%>為:

OnClientClick="if (!confirm('Are you sure you want to deposit' + <%= (commission_total)%> + 'commission into points?')) return false;"

但不允許我添加此值並說“這不是腳本”。 但我想確認一下他們要存多少錢。 我怎樣才能做到這一點?

您可以從使用JavaScript的任何地方輸入用戶輸入的值。 假設用戶正在將值輸入到如下所示的某些文本框中: <asp:Textbox runat="server" ID="myAmount" /> 然后,我們可以像這樣獲取值: document.querySelector('input[id$="myAmount"]').value 因此,您可以按以下方式使用它:

OnClientClick="if (!confirm('Are you sure you want to deposit' + document.querySelector('input[id$="myAmount"]').value + 'commission into points?')) return false;"

這是可能的解決方案之一。 由於OnClientClick事件發生在回發之前,因此您必須使用JavaScript進行此操作。 如果您不想在JavaScript中執行此操作,則必須讓回發發生並處理一個彈出窗口以確認金額。 如果您想以這種方式進行操作,則可以考慮使用Ajax Toolkit或類似的方法在用戶單擊按鈕后打開一個窗口。

希望對您有所幫助。

更新

您可以使用隱藏字段,並使用該值更新隱藏字段。 然后,您可以從JavaScript中獲取該值並將其顯示在確認對話框中。 這是標記

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function showValue() {
            var val = document.querySelector('#<%= test1.ClientID %>').value;
            return confirm('Is this correct? ' + val);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:HiddenField runat="server" ID="test1" ></asp:HiddenField>
        <asp:Button runat="server" ID="tester" OnClientClick="showValue();" Text="Show" />
    </div>
    </form>
</body>
</html>

以及后面的代碼:

using System;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected double test;
        protected void Page_Load(object sender, EventArgs e)
        {
            test = 12.50;

            test1.Value = test.ToString();
        }
    }
}

顯然,您不必在頁面加載時分配隱藏字段的值。 您可以在最適合您所建網站的地方進行操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM