一个关于多个元素的jQuery更改事件

时间:2013-04-07 15:48:15

标签: jquery html asp-classic

我有3个文本框,所有文本框都具有相同的ID,我通过将其引入控制器数组来处理ASP

我有一个链接,在前3个下面添加了无限数量的文本框。

我目前的变更声明:

    $('input.#invent').change(function () {

适用于第一个文本框中的更改事件, 但具有相同信息的其他人在更改时不会触发

当3个以上的文本框中的任何一个发生变化时,更改事件的最佳策略是什么?

6 个答案:

答案 0 :(得分:8)

将带有#invent ID的所有三个元素更改为一个类(ID的 must to be unique ),或者它只适用于第一个元素,就像当前正在发生的那样在你的情况下。

然后,您可以定位具有.invent类的所有元素:

$('input.invent').change(function () {
   // Here, $(this) refers to the specific element of the .invent class which 'changed'
}):

详细了解ID和类选择器here之间的区别。

答案 1 :(得分:5)

由于id是唯一的,因此您应该使用class。然后,您可以使用每个类迭代您的课程并应用$(this)来定位当前的change输入:

$('input.invent').each(function () {
    $(this).change(function () {

    });
});

答案 2 :(得分:3)

让我们说你的HTML是这样的:

<input type="text" id="invent" />
<input type="text" id="invent" />
<input type="text" id="invent" />
<input type="text" id="invent1" />
<input type="text" id="invent2" />
<input type="text" id="invent3" />

现在,Id必须是唯一的。因此,将类添加到invent等所有输入中,HTML将为:

<input type="text" class="invent" />
<input type="text" class="invent" />
<input type="text" class="invent" />
<input type="text" class="invent" />
<input type="text" class="invent" />
<input type="text" class="invent" />

并调用on change事件,如:

// This would be called now for all the text-boxes
$('input.invent').change(function () {
   // Your code here
}):

如果您无法为所有文本框添加类。你只需这样做:

$("input:text").change(function () {
   // Your code here
}):

答案 3 :(得分:3)

最佳策略(95%的时间):使用一个类为多个元素添加一个侦听器。 ID应该是唯一的。为此而设计的类将在将来为您提供最大的可扩展性。

HTML:

<input type="text" name="input1" class="invent" />
<input type="text" name="input2" class="invent" />

jQuery:

$('.invent').change(function () {
   // Do magical things
});

其他5%:

如果您希望使用唯一ID或唯一字段名称,而不是如所选答案中所述的单个类,则可以为多个唯一命名的元素添加一个侦听器,如下所示:

HTML:

<input type="text" name="something1" id="invent1" />
<input type="text" name="something2" id="invent2" />
<input type="text" name="something3" id="invent3" />

您可以使用jQuery multiple selectors

$('#invent1, #invent2, #invent3').change(function () {
   // Do magical things
});

OR ,您可以使用jQuery starts with 属性选择器:

//target based on what input id starts with
$('[id^="invent"]').change(function () {
   // Do magical things
});

// OR target based on input name attribute starts with
$('input[name^="something"]').change(function () {
   // Do magical things
});

答案 4 :(得分:2)

@Eli为您回答完全匹配。如果要阅读所有文本框,则可以使用以下方法。

println!

答案 5 :(得分:0)

您不能使用ID来引用多个元素。任何HTML页面上的ID都必须是唯一的!

改为使用类: - )。

相关问题