2013-04-07 73 views
7

我有3個文本框,所有具有相同ID的,我通過將它的控制器陣列處理成ASP一個jQuery的更改事件上的多個元素

我有一個鏈接,增加了下面的第一個文本框的數量不受限制3.

我的電流變化聲明:

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

工作正常,在第一個文本框, 變化事件,但改變

時相同的信息別人不火了

當3個文本框中的任何一個發生更改時,獲取更改事件的最佳策略是什麼?

+6

*「我有3個文本框,全部使用相同的ID」*這是你的問題。不要這樣做。 'id'值**必須**在文檔中是唯一的。這是「標識符」的全部要點。 – 2013-04-07 15:50:08

+1

你確定'$('input。#invent')'有效嗎?它是無效的語法 – karthikr 2013-04-07 15:53:18

+0

我很新的jquery/JavaScript,但是它的工作。 – user2182715 2013-04-07 16:17:03

回答

7

改變所有三個要素與#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

我的理解有點偏離...幫助 – user2182715 2013-04-07 16:21:50

0

您不能使用ID引用多個元素。任何HTML頁面上的ID必須是唯一的!

改爲使用類:-)。

+0

這是正確的。只是在多個元素上添加相同的ID也是語義錯誤的。記住ID可用於鏈接頁面的特定部分,這是由錨標籤之前完成的。 不是你的答案,但請記住它,而編寫的標記 – lazyprogrammer 2013-04-07 15:52:20

+0

這在技術上是不正確,你可以使用的元素'id'屬性來捕捉多個控件。關於模板,您可以使用已知的'id'模式來捕獲多個元素。 – GoldBishop 2017-11-15 15:56:38

3

由於id是唯一的,所以應該使用class。然後你就可以在你的類使用迭代每一個和應用$(this)瞄準當前change輸入:

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

    }); 
}); 
+0

使用元素唯一'id'值可以有利於選擇何時存在元素「id」的已知模式。如'control_1235','control_12543'等爲什麼這樣做? – GoldBishop 2017-11-15 15:55:22

2

比方說你的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" /> 

,並調用上的變化事件,如:

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

在情況下,你不能對所有的添加類文本框。你凸輪乾脆這樣做:

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

@Eli答案完全匹配你。如果你想閱讀所有的文本框,那麼你可以使用下面的方法。

$('input[type=text]').each(function() { 
        $(this).change(function() { 
         alert($(this).val()); 
         $(this).focus(); 
        }); 
       }); 
+0

? ('change',function(){....});'甚至'$('input [type = text]')時似乎過於複雜,文本]')改變(函數(){...});' – GoldBishop 2017-11-15 15:57:43

相關問題