简体   繁体   English

为什么jQuery无法获得输入值?

[英]Why doesn't jquery get input value?

I have used an asp.net repeater to repeat images. 我使用过一个asp.net中继器来重复图像。

I want to get the primary key ID returned from the database upon clicking the image via jquery but it shows undefined. 我想通过jquery单击图像后从数据库返回主键ID,但它显示未定义。 I am storing image in input text field and it's getting displayed in that but not in alert. 我将图像存储在输入文本字段中,但该图像已显示在其中,但未处于警报状态。

jQuery: jQuery的:

function displayStory() {
    var txtIDValue = $(this).find('input[id$=txtID]').val();
    var id = txtIDValue;
    alert(id);
}

Repeater: 中继器:

<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 doesn't not refers to element which invoked the click event handler, it refers to window object. this不是指调用click事件处理程序的元素,而是指window对象。 You can use .call() to set the context 您可以使用.call()设置上下文

<asp:ImageButton ID="imgButtonStory" OnClientClick='displayStory.call(this);return false;' runat="server" ImageUrl='<%# "UploadedImages/"+ Eval("Image") %>' 
                         CssClass="img-responsive img-rounded" />

and in the script, You need to use .prev() as the text box is not child element of ImageButton 并且在脚本中,您需要使用.prev()因为文本框不是ImageButton子元素

var txtIDValue= $(this).prev('input[id$=txtID]').val();
//var txtIDValue= $(this).closest('div').find('input[id$=txtID]').val();

you can simply say: 您可以简单地说:

function displayStory() {
    var txtIDValue = $('input[id="txtID"]').val();
    var id = txtIDValue;
    alert(id);
}

$('input[id="txtID"]') will find the element <input type="text" id="txtID" value='whatYouAreTryingToFind' /> and create a jQuery selector for it. $('input[id="txtID"]')将找到元素<input type="text" id="txtID" value='whatYouAreTryingToFind' />并为其创建一个jQuery选择器。

Tip: In jQuery the scope of $(this) for events can be interesting, so always check exactly what it returns Scope and this in JavaScript . 提示:在jQuery中,事件的$(this)范围可能很有趣,因此请始终检查它在JavaScript中返回Scope和this的确切原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM