![](/img/trans.png)
[英]JavaScript to click a button in asp.net doesn't work in master page
[英]Calling button click from JavaScript asp.net doesn't work
我試圖通過JavaScript來調用服務器端方法,方法是先顯示一條確認消息,然后觸發頁面上的按鈕單擊以調用該函數。 但是,.click()方法似乎不起作用。 有任何想法嗎?
<script type="text/javascript">
function confirmDelete() {
var button = document.getElementById("hiddenButton");
if (confirm("Are you sure you would like to delete the row")) {
button.click();
}
}
</script>
該按鈕的定義如下
<asp:Button ID="hiddenButton" runat="server" onclick="showHiddenMessage" Text="hidden" width="100px" />
我發現的所有內容都建議這樣做。 包括這里:
http://www.comptechdoc.org/independent/web/cgi/javamanual/javabutton.html
和這里:
var button = document.getElementById('<% =hiddenButton.ClientID %>');
服務器端控件的ID在客戶端上是不同的。 如上修改代碼,然后嘗試。
修改confirmDelete()
方法,如下所示:
function confirmDelete() {
if (confirm("Are you sure you would like to delete the row")) {
__doPostBack(( 'hiddenButton', '' );
}
}
看一下Button
的ClientIDMode
屬性。 將此設置為“ 靜態”將導致按鈕以您在ASP.NET代碼中輸入的ID呈現。 https://msdn.microsoft.com/zh-CN/library/system.web.ui.control.clientidmode.aspx
<asp:Button ID="hiddenButton" runat="server" ClientIDMode="Static" onclick="showHiddenMessage" Text="hidden" width="100px" />
如果查看生成的HTML,則應看到此按鈕的ID為hiddenButton ,這將允許您的Javascript正常工作。
默認情況下,ClientIDMode值將為Inherit ,並將在ID中包含NamingContainer
。 這意味着呈現的HTML的ID將類似於Panel1_hiddenButton,並且您的Javascript無法在當前代碼中找到它。
以供參考:
但是,為什么不通過按鈕使用javascript函數呢? 我認為更好:
<script type="text/javascript">
function confirmDelete() {
if (confirm("Are you sure you would like to delete the row?")) {
return true;
}
return false;
}
和你的按鈕:
<asp:Button ID="hiddenButton" runat="server" OnClientClick="return confirmDelete();" onclick="showHiddenMessage" Text="hidden" width="100px" />
在這種情況下,如果用戶單擊“確定”按鈕,則會發生showHiddenMessage
函數。 否則,將不會發生任何事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.