2013-01-16 63 views
0
<span>This Changes as You Type in Input1</span><br> 

<input type="text" id="input1"><br><br> 

<span>This Changes as You Type Type in Input2</span><br> 

<input type="text" id="input2"><br><br> 

當用戶在輸入文本中鍵入內容時,我想讓jquery搜索上面的span標籤並在用戶輸入時動態更改它。我只是用在這個例子中的變化,因爲如果我用按鍵它留下了最後的keyPressed ..jquery/js:動態更改輸入按鍵上的範圍文本

//my jquery attempt that's not working 
$('#input1').change(function() { 
$(this).closest('span').html($(this).val()  
}); 

想知道如果我可以使用類有效地編碼會這樣,而不是重複這種改變功能爲每一個ID。例如,如果我可以讓它成爲一個班,它會改變上面最近標籤上的文字?

//Like this? 
$('.inputclass').change(function() { 
$(this).closest('span').html($(this).val()  
}); 
+1

你缺少一個右括號')'爲'.html()' –

回答

0

問題是格式錯誤的javascript。你錯過收盤).html()

$(this).closest('span').html($(this).val() 

$(this).closest('span').html($(this).val()); 
+0

好吧,這不是真的,但感謝您指出了這一點,我只是很快輸入上述作爲一個例子,它是我的代碼發佈更大,但我只想了解我將如何去做它,希望人們可以建議jQuery的功能等。 –

0

雖然.closest()會工作得很好,我建議你做以下爲您的HTML更好的結構。

<div> 
    <span>This Changes as You Type in Input1</span><br> 
    <input type="text" id="input1"><br><br> 
</div> 

<div> 
    <span>This Changes as You Type in Input2</span><br> 
    <input type="text" id="input2"><br><br> 
</div> 

Enlcose您input和它對應span的父元素。顯然,使用類,因爲它可以避免代碼冗餘。

一旦你這樣做,.closest()將正常工作,但你會更好地使用.siblings()然後。

的jQuery:

你缺少一個右括號).html(),你行需要是這樣的,

$(this).closest('span').html($(this).val())