2012-03-18 57 views
0

我想這樣做,當有人使用輸入與它相對應的文本將顯示。Jquery的鍵入多輸入

<div class="content1" style="display: block;">Content 1</div> 
<div class="content2" style="display: none;">Content 2</div> 
<div class="content3" style="display: none;">Content 3</div> 
<div class="content4" style="display: none;">Content 4</div> 

<ul class="addReview"> 
     <li><p>Input 1</p><input type="text" name="input1" value="" id="input1" autocomplete="off" maxlength="2" /></li> 
     <li><p>Input 2</p><input type="text" name="input2" value="" id="input2" autocomplete="off" maxlength="2" /></li> 
     <li><p>Input 3</p><input type="text" name="input3" value="" id="input3" autocomplete="off" maxlength="2" /></li> 
     <li><p>Input 4</p><input type="text" name="input4" value="" id="input4" autocomplete="off" maxlength="2" /></li> 
    </ul> 

我會做KEYUP功能爲每個輸入還是有辦法讓一個KEYUP功能?

回答

4

這應該爲你當前的標記做到這一點:

$('.addReview input[type="text"]').keyup(function() { 
    $('div[class^="content"]').hide(); 
    $('div.' + this.id.replace(/input/, "content")).show(); 
});​ 

演示:http://jsfiddle.net/WD3CU/

但是,如果你給的div一個共同的階級,不同的IDS這將是整潔。例如,如果所有的div有一類「內容」,並在形式「內容1」的ID,那麼你可以這樣做:

$('.addReview input[type="text"]').keyup(function() { 
    $('div.content').hide(); 
    $('#' + this.id.replace(/input/, "content")).show(); 
});​ 

它看起來相似,但更強大的(我是做的方式你目前的html可能會打破,如果你要給div額外的類)。

演示結合我建議的標記變化:http://jsfiddle.net/WD3CU/1/

而且,在我看來,這會更有意義使用.focus()事件,而不是.keyup(),使相應的div將立即顯示在用戶點擊或標籤進入其中一個輸入。

0

你必須修改你的HTML架構。它改成這樣:

<div class="content" id="content_1" style="display: none;">Content 1</div> 
<div class="content" id="content_2" style="display: none;">Content 2</div> 
<div class="content" id="content_3" style="display: none;">Content 3</div> 
<div class="content" id="content_4" style="display: none;">Content 4</div> 

<ul class="addReview"> 
    <li><p>Input 1</p><input type="text" class="input" name="input_1" value="" id="input_1" autocomplete="off" maxlength="2" /></li> 
    <li><p>Input 2</p><input type="text" class="input" name="input_2" value="" id="input_2" autocomplete="off" maxlength="2" /></li> 
    <li><p>Input 3</p><input type="text" class="input" name="input_3" value="" id="input_3" autocomplete="off" maxlength="2" /></li> 
    <li><p>Input 4</p><input type="text" class="input" name="input_4" value="" id="input_4" autocomplete="off" maxlength="2" /></li> 
</ul>​ 

然後,您可以使用下面的jQuery代碼來實現你想要做什麼:

$(".input").keyup(function() { 
    var curId = this.id.split("_")[1]; 
    $("#content_"+curId).html($(this).val()); 
    $("#content_"+curId).show(); 
});​ 

工作JSFiddle demo

+0

感謝您的幫助隊友,但是那不是真的是我要去的。輸入值與我所要做的無關。我希望當有人點擊輸入時顯示預先選擇的消息來幫助他們回答問題。有點像當你問一個關於計算器的問題時,右邊是如何給你提示你的標題,然後是body,然後是標籤。謝謝您的幫助! – Claremont 2012-03-18 05:23:04

0

你必須綁定到一個共同選這樣

$('.addReview input:text').keyup(function() { }); 

demo

或類選擇這樣

$('.addReview .mytextboxclass').keyup(function() { }); 

demo

或屬性選擇像nnnnnn's answer

$('.addReview input[type="text"]').keyup(function() { });​ 

demo