2011-08-08 34 views
0

我正在使用一個非常簡單的jQuery實時預覽方法,該方法非常出色。但是,如何在不必爲每個輸入重複實時預覽代碼的情況下輸入多個輸入?如何在不重複代碼的情況下進行多個實時預覽?

我目前有:

$(function() { 
    $(".input-1").keyup(function() { 
     var word=$(this).val(); 
     $(".code-1").html(word); 
     return false; 
    }); 
}); 

<div class="wrapper"> 
    <form class="comments"> 
     <label for="input-1">Content:</label><input name="input-1" id="input-1"></input> 
    </form> 
    <h3>Codes:</h3> 
    <code><pre>&lt;h2&gt;<span class="code-1"></span>&lt;/h2&gt;</pre></code> 
</div>  

我要實現的(最多20個輸入)什麼:

<div class="wrapper"> 
    <form class="comments"> 
     <label for="input-1">Content:</label><input name="input-1" id="input-1"></input> 
     <label for="red">Content:</label><input name="red" id="blue"></input> 
     <label for="blue">Content:</label><input name="blue" id="blue"></input> 
    </form> 
    <h3>Codes:</h3> 
    <code><pre>&lt;h2&gt;<span class="input-1"></span>&lt;/h2&gt; 
    &lt;h2&gt;<span class="red"></span>&lt;/h2&gt; 
    &lt;h2&gt;<span class="blue"></span>&lt;/h2&gt; 
    </pre></code> 
</div> 
+0

順便說一句,用於''

+0

@mu太短謝謝!! – muudless

回答

1

基本上你需要一兩件事情:

  1. 一個選擇處理您關心的元素的關鍵點
  2. 一種提取給定在通用選擇正確的ID的編號1

有許多方法,以每個這些,例如第一個可使用的東西如jQuery attribute starts with,jQuery的find來實現,而第二個是簡單的字符串操作問題,可以用JavaScript Regular Expressions或JavaScript String methods解決。

這裏僅僅是一個例子

$(function() { 
     // Find all inputs whose name attribute begins with 'input-' 
     $("input[name^='input-']").keyup(function() { 
      var word=$(this).val(); 

      // Split the string using the '-' delimiter, and grab the second token 
      var number = $(this).attr("name").split('-')[1]; 

      // Select element(s) with the class name 'code-' + the number found above 
      $(".code-" + number).html(word); 
      return false; 
     }); 
    }); 
+0

如果類名不是'input-1,2,3等',而是他們有自己的名字,比如'donkey''monkey'等? – muudless

+0

請修改您的問題以反映此更改,並指出您要選擇的控件還有什麼共同之處。例如,是否要在class =「comments」的表單中選擇所有輸入控件? –

+0

當然,更改原始帖子中的更改。不,我不需要選擇所有的輸入控件。感謝那。 – muudless

相關問題