简体   繁体   English

如何通过jQuery / javascript在ASP.NET转发器中选择特定的html元素?

[英]How to select a specific html element in an ASP.NET repeater through jQuery/javascript?

I have an ASP.NET Repeater control, where a number of the following instances of code are generated/created in each ItemTemplate. 我有一个ASP.NET Repeater控件,在每个ItemTemplate中生成/创建了许多以下代码实例。

I am trying to create a function in jQuery/javascript, where the value in the 'qualityBox' text box, is incremented each time the up arrow is clicked. 我试图在jQuery / javascript中创建一个函数,其中'qualityBox'文本框中的值在每次单击向上箭头时递增。 With my code, this only works for the first 'ItemTemplate' instance - ie the first row in my Repeater. 对于我的代码,这仅适用于第一个“ ItemTemplate”实例-即我的Repeater中的第一行。

Could anyone kindly guide me in being able to make this work for each row in the Repeater? 任何人都可以指导我能够为Repeater中的每一行做这项工作吗? In other words, that the button pressed in a row makes the 'quantityBox' in that respective row only increment by 1. 换句话说,连续按下按钮会使该行中的“ quantityBox”仅增加1。

Thanks! 谢谢!

The problem with your code is that your using ID. 代码的问题在于您的使用ID。 Id's are suppose to be unique. Id的假设是独一无二的。 Therefore, when jQuery finds the first one, that's the one it uses. 因此,当jQuery找到第一个时,即使用它。 You need something that is meant to be repeatable, such as class. 你需要一些可重复的东西,比如课堂。

<ItemTemplate>
    <div>
        <input type="text" id="quantityBox" value="0"/>
        <input type="button" class="upButton"/>
    </div>
</ItemTemplate>

Next up, you have to be able to select the correct quantity box. 接下来,您必须能够选择正确的数量框。

 $(".upButton").click(function () {
     var quantityBox = $("#quantityBox", $(this).parent());
     var currentValue = quantityBox.val();
     quantityBox.val(parseInt(currentValue) + 1);
 });

This first thing to do is change the selector to add to click event to .upButton. 首先要做的是更改选择器以将click事件添加到.upButton。 This will attach the event to all instances of .upButton rather than just the first. 这会将事件附加到.upButton的所有实例,而不仅仅是第一个.upButton。

Next, why perform the DOM lookup twice when you can create a variable and just use that? 接下来,为什么在创建变量时只执行两次DOM查找并使用它?

Third, It's ok to keep ID for quantityBox because I've added a context parameter. 第三,可以保留quantityBox的ID,因为我添加了上下文参数。 This is saying get the parent element of the clicked element, which in this case will be a td. 这就是说获取clicked元素的父元素,在这种情况下将为td。 Then, only look for #quantityBox inside of that element. 然后,只查找该元素内的#quantityBox。

Give that a shot. 试一试。

I would make a data-attribute on the qty box that has an ID of some sort and then also attach that id to the element that has the up arrow so you have a relationship between the two. 我会在qty框上创建一个具有某种ID的数据属性,然后将该id附加到具有向上箭头的元素,这样你就可以在两者之间建立关系。

<ItemTemplate>
    <input type="text" id="quantityBox" data-elementID="$$" value="0"/>
    <input type="button" data-elementID="$$" id="upButton"/>
</ItemTemplate>

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

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