[英]Why doesn't jquery get input value?
我使用過一個asp.net中繼器來重復圖像。
我想通過jquery單擊圖像后從數據庫返回主鍵ID,但它顯示未定義。 我將圖像存儲在輸入文本字段中,但該圖像已顯示在其中,但未處於警報狀態。
jQuery的:
function displayStory() {
var txtIDValue = $(this).find('input[id$=txtID]').val();
var id = txtIDValue;
alert(id);
}
中繼器:
<asp:Repeater ID="rptrImages" runat="server">
<ItemTemplate>
<div class="col-md-4">
<div class="thumbnail">
<input type="text" id="txtID" value='<%#Eval("ID")%>' />
<asp:ImageButton ID="imgButtonStory" OnClientClick='displayStory();return false;' runat="server" ImageUrl='<%# "UploadedImages/"+ Eval("Image") %>'
CssClass="img-responsive img-rounded" />
</div>
</div>
</ItemTemplate>
</asp:Repeater>
this
不是指調用click事件處理程序的元素,而是指window
對象。 您可以使用.call()
設置上下文
<asp:ImageButton ID="imgButtonStory" OnClientClick='displayStory.call(this);return false;' runat="server" ImageUrl='<%# "UploadedImages/"+ Eval("Image") %>'
CssClass="img-responsive img-rounded" />
並且在腳本中,您需要使用.prev()
因為文本框不是ImageButton
子元素
var txtIDValue= $(this).prev('input[id$=txtID]').val();
//var txtIDValue= $(this).closest('div').find('input[id$=txtID]').val();
您可以簡單地說:
function displayStory() {
var txtIDValue = $('input[id="txtID"]').val();
var id = txtIDValue;
alert(id);
}
$('input[id="txtID"]')
將找到元素<input type="text" id="txtID" value='whatYouAreTryingToFind' />
並為其創建一個jQuery選擇器。
提示:在jQuery中,事件的$(this)
范圍可能很有趣,因此請始終檢查它在JavaScript中返回Scope和this的確切原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.