動態指定超連結參數的幾種方法(Passing a JavaScript variable into href of )

來源:互聯網
上載者:User

情景:有些環境下我們需要根據頁面中JavaScript變數的值來確定某個(某些)超連結的參數,如“http://www.bla.com/test.aspx?var1=”中,究竟var1等於多少,要根據JavaScript變數來判定

 

方法一:很簡單,用戶端指令碼

<a href="#" onclick="redirectURL();" class="parent">Mark</a> 

 

function redirectURL(){
    var jsvar1;
    var jsvar2;
    window.location="http://www.bla.com/test.aspx?var1="+jsvar1;//jsvar1為JavaScript變數
    }

 

方法二:在服務端Load時賦值 The easiest way would be to add the runat="server" property to the anchor and set the href in the CodeBehind

 

<a id="yourAnchor" href="#" class="parent" runat="server">Mark</a>

 

private void Page_Load(object sender, System.EventArgs e)
{
 yourAnchor.HRef = redirectURL();
}

private string redirectURL()
{
 string jsvar1 = "";
 string jsvar2 = "";

 return "http://www.bla.com/test.aspx?var1=" + jsvar1;
}

 

方法三:客戶抱怨說頁面上這種超連結很多,不適合為每個超連結寫一段onclick的Script,想了一下,還有種方法可以使大量動態超連結的管理方便一點:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
<script language="javascript" type="text/javascript">
// <!CDATA[
var jsvar1="222"
function redir(href)
{
    document.getElementById("Hidden1").value=(href+jsvar1);
    document.getElementById("Button1").click();
}

// ]]>
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <a href="http://www.bla.com/test.aspx?var1=" onclick="redir(this.href); return false;">Mark</a> 
    </div>
    <asp:Button style="display:none" ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    <input id="Hidden1" type="hidden" runat="server" />
    </form>
</body>
</html>

 

 

protected void Button1_Click(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(Page, this.GetType(), "key", "window.location='"+this.Hidden1.Value+"'", true);
}

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.