2015-04-01 28 views
1

我目前得到的是一個問題,我想要更改id與輸入類型匹配的每個元素值。請看看我的jsFiddle,這應該爲你清理很多。問題是值不會改變所有輸入類型,它只會改變該ID的第一個輸入類型。嘗試使用.each函數,但沒有幫助。更改具有相同編號的輸入類型的所有值

HTML

<input type="text" id="first" value="tesdafsdf" /> 
<input type="text" id="second" /> 
<input type="text" id="second" /> 
<input type="text" id="second" /> 
<input type="text" id="second" /> 
<input type="text" id="second" /> 
<input type="text" id="second" /> 
<input type="text" id="second" /> 
<input type="text" id="second" /> 

jQuery的

$('#first').keyup(function() { 
    updateSearch(); 
}); 

var updateSearch = function() { 
    $('#second').each(function(index, value) { 
     this.value = $('#first').val(); 
    }); 
}; 

//Change the values for testing purpose 
updateSearch(); 

http://jsfiddle.net/ZLr9N/377/

+3

ID必須是相同的..使用類 – 2015-04-01 09:51:58

+0

@ArunPJohny等待什麼實際工作,你們能不能進一步elleborate這是爲什麼?這對我來說毫無意義。 – Jordy 2015-04-01 09:53:24

+0

這有一些解釋** [Id必須是唯一的](http://programmers.stackexchange.com/a/127180)** – 2015-04-01 09:55:07

回答

7

ID被用於唯一地標識一個元件,使得元件的ID必須獨一無二

它在文檔中必須是唯一的,並且通常用於使用getElementById檢索 元素。 ID的其他常見用法包括使用 元素的ID as a selector在使用CSS對文檔進行樣式設置時。

當你必須對多個元素進行分組時,最簡單的方法之一就是使用class屬性。

當你使用一個id選擇器時,它只會返回與ID匹配的第一個元素其餘元素將被忽略。

所以元素的

$('.first').keyup(function() { 
 
    updateSearch(); 
 
}); 
 

 
var updateSearch = function() { 
 
    $('.second').val($('.first').val()); 
 
}; 
 

 
//Change the values for testing purpose 
 
updateSearch();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" class="first" value="tesdafsdf" /> 
 
<input type="text" class="second" /> 
 
<input type="text" class="second" /> 
 
<input type="text" class="second" /> 
 
<input type="text" class="second" /> 
 
<input type="text" class="second" /> 
 
<input type="text" class="second" /> 
 
<input type="text" class="second" /> 
 
<input type="text" class="second" />

+0

我想非常感謝您的意見,這是有價值的信息,並會真正幫助我改進!我需要等待8分鐘才能接受你的答案。 – Jordy 2015-04-01 09:58:16

3

不幸的是HTML元素的ID的需要是不同的,他們是爲了是唯一的標識符。類然而可以應用於多個元素,像這樣:

HTML

<input type="text" id="first" value="tesdafsdf" /> 
<input type="text" class="second" /> 
<input type="text" class="second" /> 
<input type="text" class="second" /> 
<input type="text" class="second" /> 
<input type="text" class="second" /> 
<input type="text" class="second" /> 
<input type="text" class="second" /> 
<input type="text" class="second" /> 

的Javascript

$('#first').keyup(function() { 
    updateSearch(); 
}); 

var updateSearch = function() { 
    $('.second').each(function(index, value) { 
     this.value = $('#first').val(); 
    }); 
}; 

//Change the values for testing purpose 
updateSearch(); 
+3

爲什麼「不幸」? :P – nicael 2015-04-01 09:56:24

+0

從來不知道這一點甚至在js/jquery/html中非常重要,感謝您爲我清除它! – Jordy 2015-04-01 09:59:17

相關問題